c# - 动态类型转换

标签 c#

为什么最后两行不行给我

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/

相关文章:

C# Application.Restart() 启动程序两次

c# - 如何在 C# 中添加自定义标签将 JSON 转换为 XML

c# - 具有动态参数的 Asp.net mvc Action

c# - 使用 EF Core 和 MySQL 实现行版本的更好方法?

c# - 分支执行后如何返回管道根?

c# - select/epoll/kqueue 的 C# 等效函数是什么?

c# - 查询中的 linq to sql 报告表

c# - 如果操作首先完成,则使用 RegisterWaitForSingleObject

c# - 为位于 PageFooter 部分的 TableObject 执行脚本时出错

c# - 有没有更好的方法来实现 Shift+Tab 或减少缩进?