【发布时间】:2017-01-03 08:04:17
【问题描述】:
我是 C# 的新手。我正在尝试创建一个通用类。我有三个类和一个 Main/Generic 类。
三类
public class A
{
public string Name { get; set; }
public string Address { get; set; }
public A(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class B
{
public string Name { get; set; }
public string Address { get; set; }
public B(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
public class C
{
public string Name { get; set; }
public string Address { get; set; }
public C(string _name, string _address)
{
Name = _name;
Address = _address;
}
}
通用类
public class GenericClass<T>
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
}
我已经成功创建了一个 Generic 类。
class Program
{
static void Main(string[] args)
{
A objA = new A("Mohit", "India");
GenericClass<A> objGenericClass = new GenericClass<A>(objA);
Console.ReadLine();
}
}
现在,如果我需要在 Generic 类中使用 Class A/B/C 属性。我该如何使用它?我知道类引用类型决定运行时。所以,我不能以下面的方式使用它。但是,还有其他方法吗?
public class GenericClass<T>
{
public GenericClass(T obj)
{
DynamicObject = obj;
}
public T DynamicObject { get; set; }
public void UseClassPro()
{
Console.WriteLine("Address " + DynamicObject.Address);//Compile time error here.
}
}
【问题讨论】: