我应该如何声明我的方法需要任何课程?

时间:2014-03-28 11:47:29

标签: c# class methods

Method需要任何string我们写

void method(string str)
{
str="OK";
}

我有method,需要class。 我method的一小部分:

Void Post()
{
responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}

T - 必须是class。 但我不知道如何宣布我的method需要class

3 个答案:

答案 0 :(得分:3)

使您的方法通用并添加通用parameter constraint

void Post<T>()
   where T: class
{
    responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
    // ...
}

您可以使用任何类对其进行参数化:

Post<FooClass>(); // OK if FooClass is a class
Post<int>(); // fail, because integer is a value type

答案 1 :(得分:2)

使其成为通用:

void Post<T>()
{
    responsefromserver = new JavaScriptSerializer.Deserialize<T>(sr.ReadToEnd());
}

然后使用它:

 Post<YourClass>();

如果需要,您可以constraint使用通用方法。

答案 2 :(得分:0)

您只是将依赖项作为参数或在您的情况下注入 - 更好地注入反序列化器,并且可能不在Post()方法级别上,而是在类构造函数级别上,然后在Post()中重用。