【问题标题】:Override static class member and acces through generics覆盖静态类成员并通过泛型访问
【发布时间】:2016-06-11 15:51:17
【问题描述】:

描述我的问题的最简单方法是使用示例代码。我知道这不会编译,但我需要一个类似的选项

abstract class Foo 
{
protected abstract static  ElementName {get;} 
}
class Bar : Foo
{
protected static override ElementName
{
    get
    {
        return "bar";
    }
}
}
class Baz<T> where T : Foo
{
public string ElementName 
{
    get
    {
        return T.ElementName;
    }
}
}

问候

【问题讨论】:

标签: c# generics static


【解决方案1】:

这不能以您想要的方式完成,但您可以使用反射实现类似的效果。以下示例为您的问题提供了两种可能的解决方案(更新):

abstract class Foo
{
    protected abstract string _ElementName { get; }

    public static string GetElementName<T>() where T : Foo, new()
    {
        return typeof(T).GetProperty("_ElementName", BindingFlags.Instance | BindingFlags.NonPublic)?
                        .GetValue(new T()) as string;
    }

    public static string GetStaticElementName<T>() where T : Foo, new()
    {
        return typeof(T).GetProperty("ElementName", BindingFlags.Static | BindingFlags.NonPublic)?
                        .GetValue(null) as string;
    }
}

class Bar : Foo
{
    protected static string ElementName
    {
        get
        {
            return "StaticBar";
        }
    }

    protected override string _ElementName
    {
        get
        {
            return "Bar";
        }
    }
}

class FooBar : Bar
{
    protected static string ElementName
    {
        get
        {
            return "StaticFooBar";
        }
    }

    protected override string _ElementName
    {
        get
        {
            return "FooBar";
        }
    }
}

class Baz<T> where T : Foo, new()
{
    public string ElementName
    {
        get
        {
            return Foo.GetElementName<T>();
        }
    }

    public string StaticElementName
    {
        get
        {
            return Foo.GetStaticElementName<T>();
        }
    }
}

...

Console.WriteLine(new Baz<Bar>().ElementName); // Bar
Console.WriteLine(new Baz<FooBar>().ElementName); // FooBar
Console.WriteLine(new Baz<Bar>().StaticElementName); // StaticBar
Console.WriteLine(new Baz<FooBar>().StaticElementName); // StaticFooBar

【讨论】:

  • 谢谢,这应该是解决方案。但是GetProperty 发现非值情况没有处理
  • 什么意思,能举个例子吗?
  • 如果调用GetProperty,但没有属性,则返回null。 GetValue 方法现在会引发 NullReferenceException,是吗?
  • 是的,它会的。在GetProperty方法后面加上null-conditional operator-?,这样如果返回null,链式方法根本不会被调用
猜你喜欢
  • 2012-11-15
  • 2018-01-02
  • 1970-01-01
  • 2010-09-06
  • 2016-01-19
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多