C#泛型类型属性 [英] C# Property with Generic Type
问题描述
我有一个类:
公共类class1
{
公共字符串Property1 {获取;集;}
公众诠释Property2 {获取;集;}
}
将被实例化的:
变种C =新1级();
c.Property1 =嗒嗒;
c.Property2 = 666;
所以原谅(我是新来的仿制药),我需要另一个类与通用类型的属性,使Property1或Property2可以用来设置Property3:
公共类的Class2
{
公共GenericType Property3 {获取;集;}
}
我希望能够为:
VAR C2 =新的Class2();
任何类型的c2.Property3 = c1.Property2 //任何财产。
@bytenik我认为发端却要求3类被定义为包含一个通用性。当他/她有从1类或类2的属性,在这种情况下,是一个字符串/ int值,3类的属性能够处理这两种情况。
这样, 公共类Class3的< T>
{
公共牛逼Property3 {获取;集;}
}
我觉得意图是海报要做到这一点:
Class3.Property3 = Class2.Property2
我觉得海报将需要它转换为类型T的这项工作虽然。
看被张贴为例链接:<一href="http://stackoverflow.com/questions/271347/making-a-generic-property">http://stackoverflow.com/questions/271347/making-a-generic-property
下面是你可以做的:
命名空间GenericSO
{
公共类的Class1
{
公众诠释property1 {获取;集;}
}
公共类类2&LT; T&GT;
{
公共牛逼property2 {获得;组; }
}
类节目
{
静态无效的主要(字串[] args)
{
1级C1 =新1级();
c1.property1 = 20;
等级2&LT; INT&GT; C2 =新的Class2&LT;诠释&GT;();
c2.property2 = c1.property1;
}
}
}
请注意您的模板property2得到property1的价值。 你要告诉它什么样的通用的。
I have a class:
public class class1
{
public string Property1 {get;set;}
public int Property2 {get;set;}
}
Which will be instantiated:
var c = new class1();
c.Property1 = "blah";
c.Property2 = 666;
So bear with me (I am new to generics), I need another class with a property of a generic type so that Property1 or Property2 can be used to set Property3:
public class Class2
{
public GenericType Property3 {get;set;}
}
I want to be able to:
var c2 = new class2();
c2.Property3 = c1.Property2 // Any property of any type.
@bytenik I think the originator is asking that class3 be defined to contain a generic property. That way when he / she has a property from class1 or class2 which in this case is a string / int that class3's property could handle either case.
public class Class3<T>
{
public T Property3 {get;set;}
}
I think the intent is the poster wants to do this:
Class3.Property3 = Class2.Property2
I think the poster will need to cast it to type T for this to work though.
Look at the link that was posted for an example: http://stackoverflow.com/questions/271347/making-a-generic-property
Here is what you can do:
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;
}
}
}
Notice how your template property2 gets the value of property1. You have to tell it what kind of generic.
这篇关于C#泛型类型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!