C#访问通用对象的属性 [英] C# Access the Properties of a Generic Object
问题描述
我有一种计算每个供应商,客户和制造商拥有的联系数量的方法(这是一种尝试使解释变得更容易的方案!)
I have a method that counts the number of Contacts each Supplier, Customer and Manufacturer has (this is a scenario to try make explaining easier!)
所有模型都是由Linq to SQL类创建的.每个供应商,客户和制造商都可以有一个或多个联系人
The models are all created by Linq to SQL classes. Each Supplier, Customer and Manufacturer may have one or more Contacts
public int CountContacts<TModel>(TModel entity) where TModel : class
{
return entity.Contacts.Count();
}
以上内容当然不起作用,因为实体"是通用的,并且不知道其是否具有联系人"属性.有人可以帮助您实现这一目标吗?
The above of course doesnt work, because the 'entity' is generic and doesnt know whether it has the property 'Contacts'. Can someone help with how to achieve this?
推荐答案
一种简单的方法是将接口附加到泛型中正在实现的类.
An easy way would be to attach an interface to the classes being implemented in the generic.
public int CountContacts<TModel>(TModel entity) where TModel : IContacts
interface IContacts
{
IList<Contact> Contacts {get;} //list,Ilist,ienumerable
}
这篇关于C#访问通用对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!