How to access static methods of generic types

2019-06-15 16:31发布

public class BusinessObjects<O>
    where O : BusinessObject
{
    void SomeMethod()
    {
        var s = O.MyStaticMethod(); // <- How to do this?
    }
}

public class BusinessObject
{
    public static string MyStaticMethod()
    {
        return "blah";
    }
}

Is there a correct object oriented approach to accomplishing this or will I need to resort to reflection?

EDIT: I went too far in trying to oversimplify this for the question and left out an important point. MyStaticMethod uses reflection and needs the derived type to return the correct results. However, I just realized another flaw in my design which is that I can't have a static virtual method and I think that's what I would need.

Looks like I need to find another approach to this problem altogether.

3条回答
孤傲高冷的网名
2楼-- · 2019-06-15 16:48

The reason you can't reference the static member like this:

O.MyStaticMethod(); 

Is because you don't know what type O is. Yes, it inherits from BusinessObject, but static members are not inherited between types, so you can only reference MyStaticMethod from BusinessObject.

查看更多
Ridiculous、
3楼-- · 2019-06-15 16:57

You can't access a static method through a generic type parameter even if it's constrained to a type. Just use the constrained class directly

var s = BusinessObject.MyStaticMethod();

Note: If you're looking to call the static method based on the instantiated type of O that's not possible without reflection. Generics in .Net statically bind to methods at compile time (unlike say C++ which binds at instantiation time). Since there is no way to bind statically to a static method on the instantiated type, this is just not possible. Virtual methods are a bit different because you can statically bind to a virtual method and then let dynamic dispatch call the correct method on the instantiated type.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-06-15 17:08

If you are forcing O to inherit from BusinessObject, why not just call it like this:

void SomeMethod()
{
    var s = BusinessObject.MyStaticMethod(); // <- How to do this?
}
查看更多
登录 后发表回答