如何定义类型T必须具有字段“ID”

时间:2013-08-21 12:02:32

标签: c# .net generics

此示例:

public static void createDictionary<T>(IEnumerable<T> myRecords)
            where T: T.ID // Wont Compile
        {
            IDictionary<int, T> dicionario = myRecords.ToDictionary(r => r.ID);


            foreach (var item in dicionario)
            {
                Console.WriteLine("Key = {0}",item.Key);

                Type thisType = item.Value.GetType();

                StringBuilder sb = new StringBuilder();

                foreach (var itemField in thisType.GetProperties())
                {
                    sb.AppendLine(string.Format("{0} = {1}", itemField.Name, itemField.GetValue(item.Value, null)));
                }

                Console.WriteLine(sb);
            }

        }

如何强制传递的类型作为参数有一个名为“ID”的字段?

4 个答案:

答案 0 :(得分:9)

您可以创建一个界面:

public interface IWithID
{
    // For your method the set(ter) isn't necessary
    // public int ID { get; set; } 
    public int ID { get; }
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
        where T: IWithID

您需要以这种方式使用属性,而不是字段。

或者显然你可以使用基类型......

public abstract class WithID
{
    // public int ID; // non readonly
    public readonly int ID; // can even be a field
}

public static void createDictionary<T>(IEnumerable<T> myRecords)
        where T: WithID

另一种解决方案是传递委托:

public static void createDictionary<T>(IEnumerable<T> myRecords, 
                                       Func<T, int> getID)

然后您使用GetID获取ID,例如myRecords.ToDictionary(getID)

答案 1 :(得分:5)

从已定义ID的{​​{3}}继承。

public interface IIDInterface {
     int ID { get; set; }
}


public static void createDictionary<T>(IEnumerable<T> myRecords)
            where T: IIDInterface

答案 2 :(得分:0)

where语法用于表示该类基于其他类。所以你需要一个基类:

public abstract class IDBaseClass
{
    public int ID { get; set; }
}

然后将其更改为以下内容:

where T : IDBaseClass

然后,您在那里使用的类型只需要基于该类。现在,如果你不能构建一个抽象类,因为你的类型已经基于某些东西,你可以使用一个接口:

public interface IIDInterface
{
    int ID { get; set; }
}

您可以将where语法更改为:

where T : IIDInterface

那么使用这个泛型类的类型只需要实现该接口。

答案 3 :(得分:0)

继承http://msdn.microsoft.com/en-us/library/ms173149.aspx

你需要一个“基类”或“接口”,它具有所有类实现的属性ID

where T : BaseClassWithID

where T : IInterfaceWithID