C#反射从接口获得具体类的静态属性

问题描述

| 我有一个界面:
interface IInterface 
{
    string Name { get; }
}
由通用抽象类实现:
public class BInterface<T> : IInterface
{
    static BInterface() 
    { 
        // Or anything that would be implementation class specific
        Name = typeof(BInterface<>).GetType().Name;  
    }
    public static string Name { get; private set; }
    string IInterface.Name { get { return Name; } }
}
依次在具体的类中实现:
public class CInterface : BInterface<int> 
{
}
我知道如何通过\'type.IsAssignableFrom \',\'!type.IsInterface \'和\'!type.IsAbstract \'来获取对具体类的引用,但是据我所知。 我需要通过反射获取任何具体类的静态Name属性的VALUE。但是,对于我那可怜的大脑,我无法弄清楚实现此目的的代码。任何提示都会很棒。 编辑(澄清): 我知道static属性需要从基类中读取。然而.... 静态字段将包含具体类的基名称->通过反射在基类的静态构造函数中得出。当我们在整个地方都这样做时,这行得通(并且我知道如何实现)。 在这种情况下,由于工厂实现的某些(其他)要求,我试图建立一个工厂类,该类需要了解此静态字段,并且需要通过反射来获取它。 编辑(再次)扩展代码: 这是我尝试完成的几乎完整的示例(如果没有用)。
    public interface IInterface
    {
        string Name { get; }
        object Value { get; set; }
    }

    public class BInterface<T> : IInterface
    {
        static BInterface()
        {
            // Or anything that would be implementation class specific
            Name = typeof(BInterface<>).GetType().Name; // Should be CInterface,DInterface depending on which class it is called from.
        }

    string IInterface.Name { get { return Name; } }
    object IInterface.Value { get { return Value; } set { Value = (T)value; } }

    public static string Name { get; private set; }
    public T Value { get; set; }
}

public class CInterface : BInterface<int>
{
}

public class DInterface : BInterface<double>
{
}

public static class InterfaceFactory
{
    private readonly static IDictionary<string,Type> InterfaceClasses;

    static InterfaceFactory()
    {
        InterfaceClasses = new Dictionary<string,Type>();

        var assembly = Assembly.GetExecutingAssembly();
        var interfaceTypes = assembly.GetTypes()
                                     .Where( type => type.IsAssignableFrom(typeof (IInterface)) 
                                         && !type.IsInterface 
                                         && !type.IsAbstract);
        foreach (var type in interfaceTypes)
        {
            // Get name somehow
            var name = \"...\";
            InterfaceClasses.Add(name,type);
        }
    }

    public static IInterface Create(string key,object value,params object[] parameters)
    {
        if (InterfaceClasses.ContainsKey(key))
        {
            var instance = (IInterface) Activator.CreateInstance(InterfaceClasses[key],parameters);
            instance.Value = value;

            return instance;
        }
        return null;
    }
}
我正在尝试解决ineach循环内IntefaceFactory的静态构造函数中的部分。希望这更加清楚。     

解决方法

这是从实例获取具体类的静态属性的方法:
var staticProperty = instance.GetType()
    .GetProperty(\"<PropertyName>\",BindingFlags.Public | BindingFlags.Static);
var value = staticProperty.GetValue(instance,null);
    ,
static
成员的工作方式与您的想法不同。它们属于基类,因此对于
static
继承的成员而言,您所尝试的是不可能的。