C#实体中的通用字段类型

时间:2017-01-04 16:08:32

标签: c# generics

我有几个字段的类:

class Entity{
   public int field1 {get; set;}
   public int field2 {get; set;}
   public int field3 {get; set;}
}

但是,我希望能够将此类与其他类型一起重用:string或bool may。 但编译器不喜欢我替换public int field1 {get; set;} with public T field1 {get;组;} 实现这一目标的最佳方法是什么?

3 个答案:

答案 0 :(得分:8)

您需要在类型上使用通用参数,如下所示:

class Entity<T> {
   public T field1 {get; set;}
   public T field2 {get; set;}
   public T field3 {get; set;}
}

然后您可以像这样重复使用:

class EntityOfInt : Entity<int> {
   ///field1 is an int
   ///field2 is an int
   ///field3 is an int
}

答案 1 :(得分:1)

您可以使用多种泛型:

public class Entity<T1, T2, T3, T4>
{
  public virtual T1 Field1 {get;set;}
  public T2 Field2 { get; set; }
  public T3 Field3 { get; set; }
  public T4 Field4 { get; set; }
}

public class Derived : Entity<int, string, bool, int>
{
    public override int Field1 { get; set; }
}

答案 2 :(得分:0)

在.NET 4及更高版本中,您可以使用动态

class Entity {
   public dynamic field1 {get; set;}
   public dynamic field2 {get; set;}
   public dynamic field3 {get; set;}
}

可能覆盖

class Foo : Entity {
public new string field1 {get; set;}
public new int field2 {get; set;}
//field3 is still dynamic
}

这样你仍然可以为这两种类型进行装箱和拆箱,并让你的领域暴露出来。如果没有覆盖,它们将保持动态。因此,您可以在一个类中拥有简单的类语法和多个无约束模板的可能性。

上面的类使用通用模板

class Entity<T1,T2,T3> 
     where T3: new()
{
   public T1 field1 {get; set;}
   public T2 field2 {get; set;}
   public T3 field3 {get; set;}
}

你可以看到这很快就会失控,

但请记住,这与class Entity<T>的方法不是类型安全的,因为动态字段将接受所有类型,并覆盖以前使用的类型。每次要将其用作对象时,您都必须将其取消装箱。

有关详细信息,请参阅MSDN

MSDN