![](/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.