c#casting to type from typename as string

sjo*_*urg 2 c# types casting typeof gettype

我想解决我的WCF服务层无法处理这样的泛型方法的事实:

public void SaveOrUpdateDomainObject<T>(T domainObject)
{           
    domainRoot.SaveDomainObject<T>(domainObject);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 类型TI认为这是"类型"类型的对象

  • typeof(T)的结果我相信这会导致T类型的非对象类型版本(我不知道怎么说这个)

Ant*_*lev 7

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

在任一情况下,

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