I'm trying to reference a member of an object of type 'ExternalSourceProvider' that's been instantiated through reflection like this:
Type type = GetProviderType(vendor);
ConstructorInfo constructorInfo = type.GetConstructor(new Type[] { typeof(NameValueCollection) });
ExternalSourceProvider vendorSourceProvider = (ExternalSourceProvider)constructorInfo.Invoke(new Object[] { requestData });
I now want to set the value for a static member of the newly instantiated object something like this:
(ExternalSourceProvider)vendorSourceProvider.App = this.App;
I get the error:
Member ExternalSourceProvider.App cannot be accessed with an instance reference, qualify it with a type name instead.
Which is because C# doesn't allow calling static methods with an instance reference
I'm trying to create a pattern where I call an "ExternalSourceProvider.App" member across all children that inherit the base class of type ExternalSourceProvider, so that "ExternalSourceProvider.App" is guaranteed identical across all inheriting children.
How can I achieve what I'm trying to do?
1 Answer 1
You need to specify the actual type you want the static member of.
Using reflection, you'll need to lookup the static property/field via reflection and call it that way. See PropertyInfo.SetValue (or FieldInfo
if it's an actual field).
All that said - static data is distasteful, and if you have to jump through piles of reflection hoops, you're probably doing something evil. Please reconsider.
-
Thanks Telastyn. This question softwareengineering.stackexchange.com/questions/335992/… more clearly indicates what I'm attempting to do. I'm trying to call into the member rather than set it, and PropertyInfo.SetValue wouldn't help. I've upvoted as you give some useful pointers. It'd be great if you're keen to look at the other question ;)Chris Halcrow– Chris Halcrow2016年11月14日 02:03:56 +00:00Commented Nov 14, 2016 at 2:03
-
@ChrisHalcrow - if it's a method you want to call, then MethodInfo.Invoke. In the end, reflection can do it all (slowly), you just take different routes.Telastyn– Telastyn2016年11月14日 02:13:23 +00:00Commented Nov 14, 2016 at 2:13
ExternalSourceProvider
in your code at compile time, you don't need reflection to get toExternalSourceProvider.App
; you'd only need reflection if you were accessing a static member of a type not known at compile time..
operator has higher precedence than the cast operator. So, I suspect the cast isn't doing what you want.