简体   繁体   English

如何定义类型T必须在C#中的通用抽象类中具有字段“ID”

[英]How to Define that a Type T must have a field “ID” in generic abstract class in C#

I am trying to create a generic class, that will allow me save/delete Customers, Products, so that I can have all the basic implementation at one place. 我正在尝试创建一个通用类,这将允许我保存/删除客户,产品,以便我可以在一个地方拥有所有基本实现。

public class Product : ItemDataService<Product>
{
public int id {get; set;}
}

public class Customer : ItemDataService<Customer>
{
public int id {get; set;}
}

public abstract class ItemDataService<T, V>
{
public T Item { get; set; }

public int Id { get; set; }

public ItemDataService(T item)
{
    Item = item;
}

public void SaveItem(T item)
{
    if (Item.Id <= 0)
    {
        InsertItem(item);
    }
}
}

How can i access the Id property of customer class in ItemDataService class, so that i can check Item.Id <= 0 如何在ItemDataService类中访问customer类的Id属性,以便我可以检查Item.Id <= 0

Define an interface ISomeInterface with a field Id , like: 使用字段Id定义接口ISomeInterface ,如:

public interface ISomeInterface
{
    int Id { get; }
}

And then you can make your abstract class implement that interface and also add a generic constraint that requires T to be an implementation of that interface, like this: 然后你可以让你的抽象类实现该接口,并添加一个通用约束,要求T作为该接口的实现,如下所示:

public abstract class ItemDataService<T> : ISomeInterface
    where T : ISomeInterface
{
    public int Id { get; set; }

    // ...

    public void SaveItem(T item)
    {
        if (Item.Id <= 0) // Id is accessible now..
        {
            InsertItem(item);
        }
    }
}

EDIT 编辑

Actually, given your interesting inheritance tree, you don't need the interface at all. 实际上,鉴于您有趣的继承树,您根本不需要接口。 You can simply add a generic constraint that enforces T to be a child of ItemDataService<T> . 您可以简单地添加一个通用约束,强制T成为ItemDataService<T> It looks funny, but it works: 它看起来很有趣,但它有效:

public abstract class ItemDataService<T>
    where T : ItemDataService<T>
{
    public int Id { get; set; }

    // ...

    public void SaveItem(T item)
    {
        if (Item.Id <= 0) // Id is accessible now..
        {
            InsertItem(item);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM