c# 转换为从类型名获取的类型作为字符串

标签 c# casting types typeof gettype

我想解决我的 WCF 服务层无法处理这样的通用方法这一事实:

public void SaveOrUpdateDomainObject<T>(T domainObject)
{           
    domainRoot.SaveDomainObject<T>(domainObject);
}

所以我构建了这个变通方法

public void SaveOrUpdateDomainObject(object domainObject, string typeName)
{           
    Type T = Type.GetType(typeName);
    var o = (typeof(T))domainObject;
    domainRoot.SaveDomainObject<typeof(T)>(o);
}

问题是这不会以某种方式编译。

我认为这是我没有完全理解两者之间区别的结果

  • T型 我相信这是一个“Type”类型的对象

  • typeof(T) 的结果 我相信这会导致 T 类型的非对象类型版本(我不知道如何准确地说)

最佳答案

您不需要 typeName:您必须传递 Type 实例,或使用 object.GetType() 来检索对象运行时类型。

无论哪种情况,

MethodInfo genericSaveMethod = domainRoot.GetType().GetMethod("SaveDomainObject");
MethodInfo closedSaveMethod = genericSaveMethod .MakeGenericMethod(domainObject.GetType());
closedSaveMethod.Invoke(domainRoot, new object[] { domainObject });

关于c# 转换为从类型名获取的类型作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1187319/

相关文章:

如果这些参数是可选的,C# 不传递参数

c++ - 删除空指针是否安全?

c# - 如何将对象值转换为类型值?

c++ - 什么类型的转换从 parent 到 child ?

c++ - 错误 : 'x' does not name a type

c++ - C# 中的 inet_addr 函数等效于什么

c# - WPF 不活动和事件

c# - 更新或插入新值

c# - 名称中带有空格的 JSON 类

haskell - (.) map const 的类型