gpt4 book ai didi

C# 反射从接口(interface)获取具体类的静态属性

转载 作者:行者123 更新时间:2023-11-30 15:44:23 24 4
gpt4 key购买 nike

我有一个界面:

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”获取对具体类的引用,但这是我所能做到的。

我需要通过反射获取任何具体类的静态名称属性的值。然而,对于我可怜的大脑的生活,我想不出代码来完成这个。任何提示都会很棒。

编辑(澄清):

我知道静态属性需要从基类中读取。然而……

静态字段将包含具体类的基名称 --> 通过基类的静态构造函数中的反射派生。这行得通(而且我知道如何实现),因为我们在各地都这样做。

在这种情况下,我试图构建一个工厂类,它需要知道这个静态字段,并且由于工厂实现的一些(其他)要求需要通过反射来获取它。

编辑(再次)扩展代码:

这是我试图完成的几乎完整的示例,如果没有用的话。

    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;
}
}

foreach 循环内 IntefaceFactory 的静态构造函数中的部分是我试图解决的问题。希望这更清楚。

最佳答案

这是如何从实例中获取具体类的静态属性:

var staticProperty = instance.GetType()
.GetProperty("<PropertyName>", BindingFlags.Public | BindingFlags.Static);
var value = staticProperty.GetValue(instance, null);

关于C# 反射从接口(interface)获取具体类的静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6104887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com