在 c# 中获取基础接口的属性
本文关键字:接口 属性 获取 | 更新日期: 2023-09-27 18:31:24
在阅读了与这个问题标题相关的所有文章后,我发现一些文章很接近,但没有一篇是完美的
。我知道如何使用反射来获取已知接口类型的属性。 我不知道的是,如何获取我不知道的接口类型的属性,直到运行时才会知道。 这是我现在正在做的事情:
SqlParameterCollection parameters = Command.Parameters;
thing.GetType().GetInterfaces().SelectMany(i => i.GetProperties());
foreach (PropertyInfo pi in typeof(IThing).GetProperties()
.Where(p => p.GetCustomAttributes(typeof(IsSomAttribute), false).Length > 0))
{
SqlParameter parameter = new SqlParameter(pi.Name, pi.GetValue(thing));
parameters.Add(parameter);
}
。但是,这假设我已经知道并期待"IThing"类型的界面。如果我在运行时之前不知道类型怎么办?
你不知道需要提前知道类型。可以在不指定类型的情况下循环访问属性:
static void Main(string[] args)
{
ClassA a = new ClassA();
IterateInterfaceProperties(a.GetType());
Console.ReadLine();
}
private static void IterateInterfaceProperties(Type type)
{
foreach (var face in type.GetInterfaces())
{
foreach (PropertyInfo prop in face.GetProperties())
{
Console.WriteLine("{0}:: {1} [{2}]", face.Name, prop.Name, prop.PropertyType);
}
}
}