使用约束泛型类型的静态方法C#

pqu*_*est 7 c# generics static constraints static-members

我有一个通用类:

public class Foo<T> where T: Interface
{

}
Run Code Online (Sandbox Code Playgroud)

T被强制实现的接口有2个静态方法.

在构造函数中,我希望能够基本上执行以下操作:

public Foo()
{
   value1 = T.staticmethod1();
   value2 = T.staticmethod2();
}
Run Code Online (Sandbox Code Playgroud)

使用我上面发布的伪代码无法实现这一点.是不是可以用这种方式调用这些静态方法?

Pao*_*lla 9

您可以使用扩展方法.这种技术被命名为伪混合.虽然扩展方法实际上是静态的,但它们"假装"为实例方法,因此您仍然需要T的具体实例.

此外,如果您希望您的界面保留其作为自我记录"合同"的角色,这是一种作弊,它指定了您的T类应具有的方法.但是它们是类型安全的(如果你没有在范围内引入IBarExtensions,你的Foo类将无法编译)

//our interface
public interface IBar {}

// the two static methods are define as extension methods
public static class IBarExtensions {
    public static string someMethod1(this IBar self) {
        return "my initialization 1";
    }
    public static string someMethod2(this IBar self) {
        return "my initialization 2";
    }
}

public class Foo<T> where T : IBar, new()
{
    public string value1 {get; private set;}
    public string value2 {get; private set;}

    public Foo() {
        T t = new T(); // we can do this because of the "new()" constraint
                           // in the class definition
                           // Alternatively we could pass an instance of T in
                           // the constructor 
                           // public Foo(T t)
        value1 = t.someMethod1();
        value2 = t.someMethod2();       
    }
}
Run Code Online (Sandbox Code Playgroud)

测试

public class TestBar : IBar {}
void Main()
{
    var c = new TestBar();

    var t = new Foo<TestBar>();
    Console.WriteLine(t.value1);
}
Run Code Online (Sandbox Code Playgroud)