Assume that we have some classes not having common interface or base class. How can we obtain names of the class wished? Is it possible? I’ve found the following code working as expected. However, I want to use it in a function by passing a class name. Is there any other way to achieve that?
MemberInfo[] members = typeof(objectWhatever).GetMembers();
foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
{
Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
}
I tried to write the following, but not working syntactically.
public static List<string> FieldNames(object obj ,string className)
{
dynamic changedObj = Convert.ChangeType(obj, Type.GetType(className));
MemberInfo[] members = typeof(changedObj).GetMembers();
foreach (MemberInfo memberInfo in members.Where(p => p.MemberType == MemberTypes.Property))
{
Console.WriteLine("Name: {0}", memberInfo.Name); // Name: MyField
}
}
First, we have to find Type
by given name, e.g.
// className either in short format: "Form" or
// in full format: "System.Windows.Forms.Form"
private static Type TypeFromName(string className)
{
if (string.IsNullOrWhiteSpace(className))
return null;
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(asm => asm.GetTypes())
.FirstOrDefault(t => t.Name == className || t.Namespace + "." + t.Name == className);
}
Then we are ready to enumerate properties: the only difference is that we use tp
- Type
found instead of hardcoded typeof(objectWhatever)
string className = ...
Type tp = TypeFromName(className);
if (tp != null)
{
var members = tp
.GetMembers()
.Where(p => p.MemberType == MemberTypes.Property);
foreach (MemberInfo memberInfo in members)
{
Console.WriteLine("Name: {0}", memberInfo.Name);
}
}
else
{
// className has not been found
}
I would like to have your experience at my age but I know it is not possible. It works like a charm. Thanks.
@snr: I suggest using Reflection and Linq: with a help of Reflection we get
Property/FieldInfo
, which we then query by Linq.Thanks a lot sir.
Sir, would you mind glancing at the following question? stackoverflow.com/questions/59550456/…