如何告诉C#查看属性的对象基类?

Edw*_*uay 1 c# generics inheritance

我在下面的指定行中收到错误" T不包含Id的定义 ",即使在我调试时,我看到"item" 确实在其基类中具有属性"Id" .

我如何在这里指定我希望C#在项目的基类中查找Id(为什么不自动执行此操作?)?

//public abstract class Items<T> : ItemBase (causes same error)
public abstract class Items<T> where T : ItemBase
{
    public List<T> _collection = new List<T>();
    public List<T> Collection
    {
        get
        {
            return _collection;
        }
    }

    public int GetNextId()
    {
        int highestId = 0;
        foreach (T item in _collection)
        {
           //ERROR: "T does not contain a definition for Id
           if (item.Id > highestId) highestId = item.Id; 
        }

        return highestId;
    }

}
Run Code Online (Sandbox Code Playgroud)

以下是如何定义类:

public class SmartForm : Item
{
    public string IdCode { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public int LabelWidth { get; set; }
    public int FormWidth { get; set; }
    ...


public abstract class Item : ItemBase
{
    public int Id { get; set; }
    public DateTime WhenCreated { get; set; }
    public string ItemOwner { get; set; }
    public string PublishStatus { get; set; }
    public int CorrectionOfId { get; set; }
    ...
Run Code Online (Sandbox Code Playgroud)

the*_*oop 12

你的问题是T没有约束,因此,在编译时,所有编译器都知道T是某种对象.如果您知道T将始终继承的类型,则可以向类定义添加泛型约束:

public abstract class Items<T> : ItemBase where T : Item
{
//....
}
Run Code Online (Sandbox Code Playgroud)

在调试时,T被实例化为具有Id属性的Item(或子类),但编译器在编译时不知道错误.