![](/img/trans.png)
[英]How to tell if you are in your own constructor, or your base class's constructor in c#
[英]How to tell C# to look in an object's base class for a property?
即使在调试时,我在指定的行下面仍收到错误消息“ 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;
}
}
这是定义类的方式:
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; }
...
您的问题是对T没有任何约束,因此,在编译时,所有编译器都知道T是某种对象。 如果您知道T将始终继承什么类型,则可以向类定义添加通用约束:
public abstract class Items<T> : ItemBase where T : Item
{
//....
}
当您调试时,T被实例化为确实具有Id属性的Item(或其子类),但是编译器在编译时不知道该错误,因此会出错。
您的通用约束有误。
public abstract class Items<T> : ItemBase
应该:
public abstract class Items<T> where T : ItemBase
发生的事情是,虽然您的班级有一系列的项目,但您的ItemBase
与T
没有关联
因为T绝对可以是任何东西,并且C#是类型安全的。 在T上使用具有id属性的类型的约束,您应该可以。 有关更多信息,请参见此处 。
您必须使用where子句指定T始终从ItemBase派生。
您不小心让Item继承了ItemBase,而不是T继承了ItemBase。 只是改变
: ItemBase
至
where T : ItemBase
这可能有帮助:-)
foreach (ItemBase item in _collection)
{
if (item.Id > highestId) highestId = (Item)item.Id;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.