class A1
{
public A1()
{ }
} class B
{
public A1 GetA1
{
get
{
return new A1();
}
}
} class C<T>
{
T m_t1;
public C(object obj)
{
B b = (B)obj;
//m_t1 = b.GetA1;// 如果我想使用这种方式来获取A1 该怎么办呢?
//m_t1 = new T();//编译没通过vs2008
//m_t1 = default(T);//貌似=null 了
m_t1 = System.Activator.CreateInstance<T>();
string strClassName = m_t1.GetType().ToString();
Console.WriteLine(string.Format("type of T is: {0}", strClassName));
}
} class Program
{
static void Main(string[] args)
{
C<A1> c = new C<A1>(new B()); Console.ReadKey();
}
}请教了, //m_t1 = b.GetA1;// 如果我想使用这种方式来获取A1 该怎么办呢?
小弟是c#菜鸟,这个c++上模版是能通过的,c# 里面也想类似的搞法,不知道该怎么弄了啊?
{
public A1()
{ }
} class B
{
public A1 GetA1
{
get
{
return new A1();
}
}
} class C<T>
{
T m_t1;
public C(object obj)
{
B b = (B)obj;
//m_t1 = b.GetA1;// 如果我想使用这种方式来获取A1 该怎么办呢?
//m_t1 = new T();//编译没通过vs2008
//m_t1 = default(T);//貌似=null 了
m_t1 = System.Activator.CreateInstance<T>();
string strClassName = m_t1.GetType().ToString();
Console.WriteLine(string.Format("type of T is: {0}", strClassName));
}
} class Program
{
static void Main(string[] args)
{
C<A1> c = new C<A1>(new B()); Console.ReadKey();
}
}请教了, //m_t1 = b.GetA1;// 如果我想使用这种方式来获取A1 该怎么办呢?
小弟是c#菜鸟,这个c++上模版是能通过的,c# 里面也想类似的搞法,不知道该怎么弄了啊?
=>
class C<T> where T : A1, new()
c的构造函数传入的参数,中的get方法获取的,
class C<T>
{
T m_t1;
public C(object obj)
{
B b = (B)obj;
//m_t1 = b.GetA1;// 如果我想使用这种方式来获取A1 该怎么办呢?
}
}
这个get方法也可以换成一个函数,但是不能实际的A1不能由new 得出。有一个函数是用来专门生成A1的,被封装在了b中。只能通过B的结构来获取A1.
class A1
{
public A1()
{ }
}
interface Get<T>
{
T GetA1 { get; }
}
class B : Get<A1>
{
public A1 GetA1
{
get
{
return new A1();
}
}
}
class C<T>
{
T m_t1;
public C(Get<T> obj)
{
m_t1 = obj.GetA1;
}
}
class Program
{
static void Main(string[] args)
{
C<A1> c = new C<A1>(new B()); Console.ReadKey();
}
}
class A1
{
public A1()
{ }
}
class B<T> where T : new()
{
public T GetA1
{
get
{
return new T();
}
}
}
class C<T> where T : new()
{
T m_t1;
public C(object obj)
{
B<T> b = (B<T>)obj;
m_t1 = b.GetA1;
}
}
class Program
{
static void Main(string[] args)
{
C<A1> c = new C<A1>(new B<A1>()); Console.ReadKey();
}
}
class A1
{
public A1()
{ }
}
class B<T> where T : new()
{
public T GetA1
{
get
{
return new T();
}
}
}
class C<T> where T : new()
{
T m_t1;
public C(B<T> obj)
{
m_t1 = obj.GetA1;
}
}
class Program
{
static void Main(string[] args)
{
C<A1> c = new C<A1>(new B<A1>()); Console.ReadKey();
}
}