Vil*_*lx- 80
那么......为什么不使用简单的继承呢?喜欢:
class MyGenericClass<T>
{
}
class MyGenericClass : MyGenericClass<int>
{
}
Run Code Online (Sandbox Code Playgroud)
这样你可以写两种方式:
var X = new MyGenericClass<string>();
var Y = new MyGenericClass(); // Is now MyGenericClass<int>
Run Code Online (Sandbox Code Playgroud)
你不能在类的定义中这样做:
var foo = new MyGenericClass(); // defaults to integer... this doesn't work
var bar = new MyGenericClass<MyEnum>(); // T is a MyEnum
Run Code Online (Sandbox Code Playgroud)
如果真的重视默认类型为 int 的隐含性,则必须使用静态工厂方法来实现,尽管我没有看到它的价值。
public class MyGenericClass<T>
{
public static MyGenericClass<T> Create()
{
return new MyGenericClass<T>();
}
public static MyGenericClass<int> CreateDefault()
{
return new MyGenericClass<int>();
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅下文,了解您如何真正无法从上述内容中受益。
var foo = MyGenericClass<MyEnum>.Create();
var bar1 = MyGenericClass.CreateDefault(); // doesn't work
var bar2 = MyGenericClass<int>.CreateDefault(); // works, but what's the point
Run Code Online (Sandbox Code Playgroud)
如果你想更进一步,你可以创建一个静态工厂类来解决这个问题,但如果你这样做只是为了提供默认类型,那么这是一个更荒谬的解决方案:
public static class MyGenericClassFactory
{
public static MyGenericClass<T> Create<T>()
{
return new MyGenericClass<T>();
}
public static MyGenericClass<int> Create()
{
return new MyGenericClass<int>();
}
}
var foo = MyGenericClassFactory.Create(); // now we have an int definition
var bar = MyGenericClassFactory.Create<MyEnum>();
Run Code Online (Sandbox Code Playgroud)
保留您的原始版本(非通用版本)并创建它的通用版本。
然后从非通用版本调用通用版本。
void Main()
{
DoSomething(2);
DoSomething(EnumValue);
}
public void DoSomething(int test) {
DoSomething<int>(test);
}
// Define other methods and classes here
public void DoSomething<T>(T test) {
Console.WriteLine(test);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13318 次 |
| 最近记录: |