简体   繁体   English

在未知对象上从BaseEntity调用通用方法

[英]Calling a Generic Method from BaseEntity on unknown object

this is what I do if I know the type; 如果我知道类型,这就是我要做的;

TypeA.Get<TypeA>(Id).Delete();

and what I am trying to do is this; 我想做的是

object ObjectA;

(BaseEntity<typeof(ObjectA)>).Get<(BaseEntity<typeof(ObjectA)>)>(Id).Delete();

which didn't work, any idea how to do this properly? 哪个不起作用,知道如何正确执行此操作吗?

You can either: 您可以:

  • use reflection to call both Get and Delete methods, or: 使用反射来调用GetDelete方法,或者:
  • use reflection to call Get and dynamic to invoke Delete 使用反射调用Get并使用dynamic调用Delete


Since you're giving up static typing either way, I'd go with the 2nd option for simplicity. 由于您都放弃了使用静态输入的方式,因此为了简单起见,我会选择使用第二个选项。

var typeA = objectA.GetType();
var fEntityType = typeof(FEntity<>).MakeGenericType(typeA);

var getMethod = fEntityType.GetMethod("Get").MakeGenericMethod(typeA);

dynamic result = getMethod.Invoke(null, new object[]{ Id });

result.Delete();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM