泛型 类: 可选类型

Generic Classes: Optional Type

在 C# 中有没有一种方法可以使用具有可选类型的泛型 class。

例如

Class:

public abstract class A<Type> : Interface where Type : new()
{
    public string Method1(int param)
    { ... }
}

致电:

A<SomeType>.Method1(9);
A.Method1(9);

我认为你应该理清你的设计思路。

您有一个泛型 class,具有完全限定的类型名称,或者您有一个非泛型 class。它是其中之一。你没有一半 classes.

所以你可以这样写:

public class A : Interface
{
    public string Method1(int param)
    { ... }
}

A a = new A();
string output = a.Method1(10);

或者如果您将 Method1 设置为静态:

string output = A.Method1(10);

然后您可以选择为通用变体派生那个:

public class B<T> : A where T : new()
{
}

B<int> b = new B<int>();
string output = b.Method1(10);