如何在c#中使用generics,其中两个不相关的类具有相同的属性?

我正在尝试编写一个通用方法

GenericMethod(T item) where T : class { (if item.value1 == "something") doSomething } 

但是我收到一个错误:

 T does not contain the definition of value1. 

我搜索了StackOverflow中的其他答案,并尝试实现一个接口,然后将方法定义更改为where T: dummyInterface

虽然这从方法中删除了错误,但在调用方法时出现错误:

我需要从两个不同的类中调用该方法: GenericMethod(customerRet)GenericMethod(vendorRet)

GenericMethod(customerRet)抛出编译错误:

 accountRet should be convertible to dummyInterface 

我也收到GenericMethod(vendorRet)相同错误。

customerRetvendorRet没有任何关联 – 没有通用接口等。

你应用的约束是class 。 在运行时,您可以传入任何类,可能包含也可能不包含名为value1的属性。 除此之外,您可以指定要使用的确切类或具有约束的属性value1的接口。

使AccountRetIDummyInterface实现IDummyInterface ,在这种情况下,您不再需要通用方法:

 PerformOperation(IDummyInterface item) { if (item.value1 == "something") DoSomething(); } 

如果由于某种原因无法更改这两个类 ,请对该方法进行两次重载:

 PerformOperation(AccountRet item) { if (item.value1 == "something") DoSomething(); } PerformOperation(VendorRet item) { if (item.value1 == "something") DoSomething(); } 

您的原始代码无法编译,因为编译器无法在编译时certificategenericsT类上有属性Value1 – 事实上,当没有约束时, 任何 T 都不是这种情况。