简体   繁体   中英

How to get Class Name given its Property

Is it possible to get the class name given the name of its property. If it is then how? Anyone can help me.

I don't think it is directly possible. You will have to search all the classes via reflection and you will have to look for that particular property in each class

If you have a PropertyInfo then you could use the DeclaringType property. If you only have some string you cannot get much from it. You will have to first get the property but to get the property you first need to get the declaring class, so you already know the declaring class.

反思是个好主意尝试阅读位于MSDN.com http://msdn.microsoft.com/zh-cn/library/ms173183(VS.80).aspx的这篇文章

Here is an example for mscorlib.dll. It finds all classes which have property named "Capacity".

Assembly asm = Assembly.Load("mscorlib.dll");
foreach (Type type in asm.GetTypes())
{
    foreach (MemberInfo mem in type.GetMembers())
    {
        if ((mem.MemberType == MemberTypes.Property) && (mem.Name == "Capacity"))
            Console.WriteLine(type);
    }
}

Or, using LINQ:

var asm = Assembly.Load("mscorlib.dll");
foreach (var type in from type in asm.GetTypes()
                     from mem in type.GetMembers()
                     where (mem.MemberType == MemberTypes.Property) &&
                        (mem.Name == "Capacity")
                     select type)
    Console.WriteLine(type);

Here is the output:

System.Text.StringBuilder
System.Collections.CollectionBase
System.Collections.ArrayList
System.Collections.ArrayList+IListWrapper
System.Collections.ArrayList+SyncArrayList
System.Collections.ArrayList+FixedSizeArrayList
System.Collections.ArrayList+ReadOnlyArrayList
System.Collections.ArrayList+Range
System.Collections.SortedList
System.Collections.SortedList+SyncSortedList
System.Collections.Generic.List`1[T]
System.IO.MemoryStream
System.IO.UnmanagedMemoryStream
System.IO.PinnedBufferMemoryStream
System.IO.UnmanagedMemoryAccessor
System.IO.UnmanagedMemoryStreamWrapper

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM