为什么最后两行不行给我
The type or namespace name 'myType' could not be found
Type myType = this.GetType();
bool test = obj is myType;
var p = (myType)obj;
最佳答案
你需要做的:
bool test = myType.IsInstanceOfType(obj);
或
bool test = myType.IsAssignableFrom(obj.GetType());
// var p = Convert.ChangeType(obj, myType); - update: this is not what the OP asked
对于第二个,您不能将表达式“转换”为编译时未知的类型。强制转换的目的是在本地引用该类型的成员。如果你不知道编译类型是什么类型(因为你正在使用 .GetType()
),那么就没有点转换,实际上这是不可能的。
关于c# - 动态类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4454332/