【问题标题】:Send Generic type to the base class?将泛型类型发送到基类?
【发布时间】:2020-11-09 11:59:01
【问题描述】:

通常这就是我为类属性制作泛型类型的方式:

我的模型看起来像:

public class CustomerProfile<T> where T : class 
{
   public T Address{ get; set; }
  }

将类型从我的客户端代码发送到泛型类型类的代码:

 var genericTypeParameter  = typeof(CustomerAddress);
 var genericBaseType = typeof(CustomerProfile);
 var genericType = genericBaseType.MakeGenericType(genericTypeParameter  );

现在我必须按如下方式创建类层次结构:

  public class Customer : CustomerProfile
  {
       public Customer Names { get; set; }
   }

现在如何将类型 CustomerAddress 类型发送到 CustomerProfile 类 Generic Type?

【问题讨论】:

  • "Send" 不是在这里使用的最佳术语。我想你想要的词是“assign
  • 当你的类实际上是 CustomerProfile&lt;T&gt; 时,还不清楚如何创建这个 public class Customer : CustomerProfile 而不会出现编译器错误。这使得这个问题有点不清楚
  • HI General.. 我得到编译错误.. 我只是把代码显示我的意图
  • 你是问如何在运行时动态创建class Customer : CustomerProfile&lt;CustomerAddress&gt;
  • 是的,杰瑞。基本上使用我上面的代码来生成泛型类型并分配给基类。

标签: c# generics


【解决方案1】:

如何将类型 CustomerAddress 类型发送到 CustomerProfile 类 Generic Type?

您只需要在声明中指定类型:

public class Customer : CustomerProfile<CustomerAddress>
{
    public Customer Names { get; set; }
}

如果您在编译时不知道CustomerAddress 类型,那么您需要将Customer 设为泛型:

public class Customer<T> : CustomerProfile<T>
{
    public Customer Names { get; set; }
}

然后以与当前获取 CustomerProfile&lt;T&gt; 相同的方式获取 Customer&lt;T&gt; 类型。

我承认,您发布的其余代码看起来很奇怪。目前尚不清楚为什么要使用反射来实例化您在编译时知道类型参数的类型。 typeof(CustomerProfile&lt;CustomerAddress&gt;) 应该与您发布的基于反射的代码一样有效。

拥有与声明类型相同类型的Names 属性似乎很奇怪。

但就为基类获取正确的类型参数而言,根据上面的示例,这是微不足道的。

【讨论】:

  • 嗨彼得:很抱歉让你感到困惑,但我实际上发布了一个修改后的代码。在编译期间我不会知道类型。
  • “我不会在编译时知道类型”——嗯,这不是你问的问题。您的问题是特定,您希望将CustomerAddress 作为类型参数传递。我将根据我对您实际意思的最佳猜测更新答案,但如果这不能解决您的问题,那么您需要解决您的问题,以便清楚。
  • 谢谢彼得。基本上我想使用我上面的 makegeneric 类型代码来生成泛型类型并将其分配给基类 CustomerProfile
  • "我想使用我上面的 makegeneric 类型代码来生成泛型类型并将其分配给基类 CustomerProfile" -- 使用你拥有的代码,唯一的这样做的方法是使派生类也通用,正如我上面解释的那样。如果你愿意介绍 .NET 的运行时类型构建,你可以在运行时创建一个继承封闭泛型类型的新类型。见stackoverflow.com/questions/13276447/…。当然,使用这种技术,您将没有编译时访问派生类型。
猜你喜欢
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 2014-03-22
  • 2019-10-07
  • 2012-09-08
  • 1970-01-01
相关资源
最近更新 更多