Get base interface properties in c #

After reading all the articles related to the title of this question, I have found several close ones, but none of them are perfect for what I am trying to accomplish.

I know how to use reflection to get the properties of the KNOWN interface type. I don't know how to get interface type properties, which I don't know, and won't know until runtime. Here's what I'm doing now:

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

      

... but, this assumes that I already know and expect an interface like "IThing". What if I don't know the type before starting?

+3


source to share


1 answer


You don't know you need to know the type in advance. You can iterate over properties without specifying the type:



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

      

+2


source







All Articles