I have the following case:
public interface IPerson { .. } public class Person : IPerson { .. } public class User : Person { .. }
Now; if I have a "User" object - how can I check if this implements IPerson using reflection? To be more precise I have an object that might have a property SomeUser, which should be of some type implementing the interface "IPerson". In my case I actually have a User, but this is what I want to check through reflection. I can't figure out how to check the property type since it is a "User", but I want to check if it implements IPerson...:
var control = _container.Resolve(objType); // objType is User here var prop = viewType.GetProperty("SomeUser"); if ((prop != null) && (prop.PropertyType is IPerson)) { .. }
(Note that this is a simplification of my actual case, but the point should be the same...)
Reflection Namespace. Contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types, for example to hook up events or to invoke methods.
Reflection provides objects that encapsulate 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. You can then invoke the type's methods or access its fields and properties.
Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations. If you use it 10'000 times in a time-critical method, I would consider to change the implementation.
Reflection in C# is used to retrieve metadata on types at runtime. In other words, you can use reflection to inspect metadata of the types in your program dynamically -- you can retrieve information on the loaded assemblies and the types defined in them.
Check the Type.IsAssignableFrom
method.
var control = _container.Resolve(objType); var prop = viewType.GetProperty("SomeUser"); if ((prop != null) && (prop.PropertyType.GetInterfaces().Contains(typeof(IPerson))) { .. }
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