Lets say I have
class Person
{
public Person(int age, string name)
{
Age = age;
Name = name;
}
public int Age{get;set}
public string Name{get;set}
}
and I would like to create a method that accepts a string that contains either "age" or "name" and returns an object with the value of that property.
Like the following pseudo code:
public object GetVal(string propName)
{
return <propName>.value;
}
How can I do this using reflection?
I am coding using asp.net 3.5, c# 3.5
Get Property Names using Reflection [C#] Method returns array of PropertyInfo objects and the property names are available through PropertyInfo.Name property. If you want to get only subset of all properties (e.g. only public static ones) use BindingFlags when calling GetProperties method.
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
Assembly; Console. WriteLine(bookAssembly); The code from earlier that uses Attribute. GetCustomAttribute() is also an example of Reflection.
GetProperty(String, BindingFlags) Searches for the specified property, using the specified binding constraints. public: virtual System::Reflection::PropertyInfo ^ GetProperty(System::String ^ name, System::Reflection::BindingFlags bindingAttr); C# Copy.
I think this is the proper syntax...
var myPropInfo = myType.GetProperty("MyProperty");
var myValue = myPropInfo.GetValue(myInstance, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With