I want to set property via .InvokeMember but I can not do this when casting is required,
public Class A{
private B? _bb;
public B? Bb{
get{return _bb;}
set {_bb=value;}
}
}
public struct B {
public B(int i){}
public static implicit operator B(int p)
{ B q = new B(p);
return q;
}
}
when I set it via Simple Code,it works.
A myA=new A();
myA.Bb=12;
but when I try to set it via InvokeMember,it does not work with casting,it just work for direct type.
this code works
A myA=new A();
myA.GetType().InvokeMember("Bb",
BindingFlags.SetProperty, null,myA, new object[] { new B(12) });
but the next line , gives error and says that it can not find property “Bb”
A myA=new A();
myA.GetType().InvokeMember("Bb",
BindingFlags.SetProperty, null,myA, new object[] { 12});
I have to use it by the last way,how should I have to do it ?
This won’t even compile. B is a reference type, thus you cannot use it as a generic argument for the
Nullable<T>class:This being said, assuming you fix your code and declare B as a value type (using a
structfor example), the problem is that Reflection doesn’t use implicit conversion operators.You may take a look at the following thread for one possible solution.
Another possibility is to invoke the
op_Implicitstatic method emitted by the compiler to convert the integer into an instance ofB: