我刚刚在dotnet上创建了Generics。当我感到困惑时,我试图学习泛型类和泛型方法。下面我贴了一个代码。
class Program
{
static void Main(string[] args)
{
Helper<int> helper = new Helper<int>();
helper.helperMethod<string>("hello Ram !");
Console.Read();
}
}
public class Helper<T>
{
public void helperMethod<T>(T input)
{
Console.WriteLine(input);
}
}
创建类的实例时,在Helper类中使用type参数。
Helper<int> helper = new Helper<int>();
如果我可以自己创建泛型方法,那么在类中使用“int”或任何其他类型参数的目的是什么。如果在创建泛型类时使用了type参数,为什么在类型参数中使用不同的数据类型与泛型方法相比?
答案 0 :(得分:6)
cnn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["name"];
类有两种有用的变体,根据预期效果更清晰:
只在类
上有一个类型参数Helper
在这种情况下,写入的public class Helper<T>
{
public void helperMethod(T input)
{
Console.WriteLine(input);
}
}
方法将导致编译错误,因为Main
仅接受Helper<int>.helperMethod
的{{1}}。
仅在方法上有一个类型参数
int
在这种情况下,input
可以接受任何类型。
答案 1 :(得分:1)
如果我可以自己创建泛型方法,在类中使用“int”或任何其他类型参数的目的是什么
没有目的。您可以轻松创建一个采用泛型参数的静态方法:
class Program
{
static void helperMethod<T>(T input)
{
Console.WriteLine(input);
}
static void Main(string[] args)
{
helperMethod<string>("hello Ram !");
helperMethod<int>(1024);
Console.Read();
}
}
另外一点:C#编译器通常足够聪明,可以找出上面那些函数调用的参数类型,所以你可以写一下:
helperMethod("hello Ram !");
helperMethod(1024);
如果在创建泛型类时使用了type参数,为什么在类型参数中使用不同的数据类型与泛型方法相比?
您发布的示例太简单了,没有任何好处。你可以有一个基于一种类型的泛型类,它可以在其中使用另一种类型的泛型方法调用。该方法调用将是在类型T上操作的类的一部分,并且该方法本身采用类型Y的参数。这个的简单示例可以是将不同类型转换为类类型的Converter类。即:
class Program
{
static void Main(string[] args)
{
var converter = new Converter<string>();
var converted_objected = converter.ConvertThis<int>(200);
Console.Read();
}
}
class Converter<T>
{
public T ConvertThis<O>(O to_convert)
{
T result = default(T);
// do stuff with to_convert and the answer ends up in result
return result;
}
}
一个过于简单的示例,它并不适用于所有类型,但我希望它可以帮助您获得图片。
此致
亚当。
答案 2 :(得分:1)
如果我可以自己创建泛型方法,在类中使用“int”或任何其他类型参数的目的是什么
generics
。 generic class or method
背后的想法只是为了避免任何类型的code bloating
。由于相同的实现可以用于多种类型,而不需要为每种类型单独实现/重载。让我们理解使用一些代码示例:此代码可以使用,因为
T
与HelperMethod
,Console.WriteLine
无关,需要object
基类型作为输入,这是所有的基类T
public class Helper<T>
{
public void helperMethod<T>(T input)
{
Console.WriteLine(input);
}
}
让我们看看可能的修改:
- 在这种情况下只需要
醇>method
或class
泛型,因为两者都是通用的,几乎没有价值,例如:
public class Helper<T>
{
public void HelperMethod(T input)
{
Console.WriteLine(input);
}
}
或者
public class Helper
{
public void HelperMethod<T>(T input)
{
Console.WriteLine(input);
}
}
- 更重要的是,这使得仿制品值得推荐
醇>Constraints
,因为这是使它们在真正意义上有用的唯一方法
public class Helper<T> where T:ICustom
{
public void HelperMethod(T input)
{
A a = input.Method1();
B b = input.Method2();
}
}
interface ICustom
{
A Method1();
B Method2();
}
Class A
{
// Fields and Properties of Class A
}
Class B
{
// Fields and Properties of Class B
}
这样做的重要性在于,泛型类型可用于调用相关方法并在泛型方法中使用输出,如上述情况中的A and B
类型可导致真正的Generic implementation
。< / p>
约束非常有用的另一个领域是Func<T,A>
,可以供用户实现,例如:
public class Helper<T>
{
public void HelperMethod(Func<T,A> input,Func<T,B> input1,T t1)
{
A a = input(t1);
B b = input1(t1);
}
}
此处Func
实施将由来电者完成,但会确保结果为Type A and B