【问题标题】:C# Property with Generic Type [duplicate]具有通用类型的 C# 属性 [重复]
【发布时间】:2011-01-03 21:01:37
【问题描述】:

我有一堂课:

public class class1
{
public string Property1 {get;set;}
public int Property2 {get;set;}
}

将被实例化:

var c = new class1();
c.Property1 = "blah";
c.Property2 = 666;

所以请耐心等待(我是泛型新手),我需要另一个具有泛型类型属性的类,以便使用 Property1 或 Property2 来设置 Property3:

public class Class2
{
public GenericType Property3 {get;set;}
}

我希望能够:

var c2 = new class2();
c2.Property3 = c1.Property2 // Any property of any type.

【问题讨论】:

标签: c# .net generics


【解决方案1】:
public class class1<T>
{
public T Property3 {get;set;}
}

关于问题的编辑版本:

如果你需要一个可以设置成任何类型的属性,这里最合理的解决方案是简单地使用 Object 类型的属性。对于 C# 编译器,无法找出您之前推送到属性设置器中的确切类型的实例。

【讨论】:

  • 你不能这样做,需要在编译时知道类型。
【解决方案2】:

@bytenik 我认为发起者要求将 class3 定义为包含通用属性。这样,当他/她拥有来自 class1 或 class2 的属性时,在这种情况下是一个 string/int,class3 的属性可以处理任何一种情况。

public class Class3<T>
{
 public T Property3 {get;set;}
}

我认为发帖人的意图是这样做:

Class3.Property3 = Class2.Property2

我认为海报需要将其转换为类型 T 才能正常工作。

查看发布的链接作为示例:Making a generic property

你可以这样做:

namespace GenericSO
{
    public class Class1
    {
        public int property1 { get;set;}

    }

    public class Class2<T>
    {
        public T property2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Class1 c1 = new Class1();
            c1.property1 = 20;

            Class2<int> c2 = new Class2<int>();

            c2.property2 = c1.property1;
        }
    }
}

注意您的模板 property2 如何获取 property1 的值。 你必须告诉它什么样的泛型。

【讨论】:

  • 你有选角的例子吗?
  • 我发布了你能做什么
  • 感谢您的帮助。这让我开始了,链接非常好。
  • 你把整个类型变成了泛型,有什么方法可以让属性泛型吗?
  • @AliAdravi - 抱歉刚刚看到您的评论,没有整个类型必须是通用的 - 请参阅:stackoverflow.com/questions/271347/making-a-generic-property
【解决方案3】:

我认为您可能误解了泛型。可以使用的另一个词是“模板”,但由于它用于 C++ 中更高级的事物,所以避免使用它。

以下将创建一个当前未定义类型 T 的泛型类。

public class Class2<T>
{
    public T Property3 { get; set; }
}

要使用它,您需要指定缺少的类型:

var x = new Class2<int>();

这将创建一个具有 int 类型的属性 Property3 的对象。

...或...

var y = new Class2<string>();

这将创建一个具有字符串类型属性 Property3 的对象。

根据您的问题,我相信您实际上想要一种类型,您可以在运行时为其分配任何类型,但这不是泛型提供的。

【讨论】:

  • @Matt Breckon 我觉得这很尴尬,因为它需要一些逻辑来决定我使用哪种类型。 @JonH 你有例子吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 2011-02-04
  • 2018-02-21
  • 2015-08-31
相关资源
最近更新 更多