如何访问泛型类型的静态方法 [英] How to access static methods of generic types

查看:118
本文介绍了如何访问泛型类型的静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class BusinessObjects< O> 
其中O:BusinessObject
{
void SomeMethod()
{
var s = O.MyStaticMethod(); //< - 如何做到这一点?



public class BusinessObject
{
public static string MyStaticMethod()
{
returnblah;






$ b

是否有正确的面向对象的方法来完成这个或我需要去反思吗?

编辑:我试图过分简化这个问题并且忽略了一个重要的观点。 MyStaticMethod使用反射并需要派生类型来返回正确的结果。然而,我刚刚意识到我的设计中存在另一个缺陷,那就是我无法使用静态虚拟方法,我认为这就是我需要的。



看起来我需要找到解决这个问题的另一种方法。 解决方案

原因是你不能像这样引用静态成员:

  O.MyStaticMethod(); 

是因为你不知道O是什么类型。是的,它从BusinessObject继承,但静态成员不在类型之间继承,所以您只能从BusinessObject引用MyStaticMethod。


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.

解决方案

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.

这篇关于如何访问泛型类型的静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆