【问题标题】:Get properties of underlying interface in c#在c#中获取底层接口的属性
【发布时间】:2014-11-22 00:18:10
【问题描述】:

在阅读了与这个问题的标题相关的所有文章后,我发现了一些接近的文章,但没有一个适合我想要完成的任务。

我知道如何使用反射来获取 KNOWN 接口类型的属性。我不知道的是如何获取我不知道并且直到运行时才知道的接口类型的属性。这是我现在正在做的事情:

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

... 但是,这假设我已经知道并且期待“ITing”类型的接口。如果我在运行前不知道类型怎么办?

【问题讨论】:

    标签: c# reflection interface


    【解决方案1】:

    你不知道需要提前知道类型。您可以在不指定类型的情况下迭代属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 2021-07-10
      • 2017-10-22
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      相关资源
      最近更新 更多