gpt4 book ai didi

c# - 动态类型转换

转载 作者:行者123 更新时间:2023-11-30 13:51:29 25 4
gpt4 key购买 nike

为什么最后两行不行给我

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com