问题描述
我只是想在C#中探索Generic类。
我试图将一个对象传递给类Test并且我正在分配 _value
客户对象。
如何在下面的write方法中检索客户对象值?
I am just trying to explore Generic class in C#.
I am trying to pass an object to the class Test and I am assigning the _value
the customer object.
How to retrieve the customer object value in write method below?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Customer
{
public int CusomerId { get; set; }
public string CustomerName { get; set; }
public int CustomerAge { get; set; }
}
public class Test<T>
{
T _value;
public Test(T t)
{
_value = t;
}
//i am trying here to get the customer object from _value which i assigned in _value
//i cant even use foreach in generic class...
public void write()
{
}
}
class Program
{
static void Main(string[] args)
{
Customer obj = new Customer();
obj.CusomerId = 1001;
obj.CustomerAge = 23;
obj.CustomerName = "Anurag";
Test<object> T1 = new Test<object>(obj);
T1.write();
Console.ReadLine();
}
}
}
请帮助我
推荐答案
public class Test<T> where T : Customer
其中T:客户
确保您只能使用 Customer
类型或从 Customer
派生的类型。
然后,在 Main
方法中更改此行:
where T : Customer
makes sure you can only use the type Customer
or types derived from Customer
.
Then, change this line in the Main
method:
Test<Customer> T1 = new Test<Customer>(obj);
更改对象
进入客户
,否则会出现编译错误。
现在,你将成为能够从泛型类中的 Customer
类访问属性。
Change object
into Customer
, otherwise you will get a compiler error.
Now, you will be able to access the properties from the Customer
class from your generic class.
这篇关于泛型类怀疑如何传递对象并获得所需的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!