开发者

C# Generics: there is no way to constrain a type to have a static method?

Could somebody kindly explain this to me, in simple words:

there is no way to constrain开发者_StackOverflow社区 a type to have a static method. You cannot, for example, specify static methods on an interface.

many thanks in advance to you lovely people :)


With generics, you can add a constraint that means the generic-type supplied must meet a few conditions, for example:

  • where T : new() - T must have a public parameterless constructor (or be a struct)
  • where T : class - T must be a reference-type (class / interface / delegate)
  • where T : struct - T must be a value-type (other than Nullable<TSomethingElse>)
  • where T : SomeBaseType - T must be inherited from SomeBaseType (or SomeBaseType itself)
  • where T : ISomeInterface - T must implement ISomeInterface

for example:

public void SomeGenericMethod<T>(T data) where T : IEnumerable {
    foreach(var obj in data) {
        ....
    }
}

it is SomeBaseType and ISomeInterface that are interesting here, as they allow you to demand (and use) functions defined on those types - for example, where T : IList gives you access to Add(...) etc. HOWEVER! simply: there is no such mechanism for things like:

  • constructors with parameters
  • static methods
  • operators / conversions
  • arbitrary methods not defined via a base-type or interface

so: you can't demand those, and you can't use them (except via reflection). For some of those dynamic can be used, though.


so, basically:

public class A{}

public class B{
  public static void Foo() {}
}

You can't write a generic constraint for T in:

public class C<T> {}

Such that you restrict to accept only A or B based on the presence or non-presence of the static method Foo().


Imagine the following not working code:

interface IWithStatic
{
    void DoIt(); // non-static
    static void DoItStatic(); // static
}

class C1 : IWithStatic
{
    void DoIt() {} // non-static
    static void DoItStatic(){} // static
}

class C2 : IWithStatic
{
    void DoIt() {} // non-static
    static void DoItStatic(){} // static

}

And, in a program :

IWithStatic myObj = GetWithAnyMethod(); // Return a C1 or C2 instance

myObj.DoIt(); // working, as the runtime type is used (either C1 or C2);

but with the static... how can the compiler interpret this :

IWithStatic.DoItStatic(); // Not knowing which type to use

Do you see what's the problem now ?


It is not possible to have:

public interface IInterface {
   static void Method();
}

This is because you are not allowed/able to constrain implementing classes to methods being static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜