如何实例化泛型类 [英] How do I instantiate a generic class

查看:104
本文介绍了如何实例化泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨 -



我正在学习更多关于泛型的知识,我想知道如何实例化泛型类。这是班级



Hi -

I'm learning more about generics and I'm wondering how to instantiate a generic typed class. Here is the class

public class MyGenericCommand<T> : ICommand<T,T> where T : IMyBaseStuff<IBaseStuff>
{
 ///reset of class code here
}





In另一堂课会想要一些像



In another class would want some thing like

private MyGenericCommand<some class> _command;





谢谢



我有什么试过:



c#Generic on variable declaration,这可能吗? - 堆栈溢出 [ ^ ]

推荐答案

请参阅泛型(C#编程指南)| Microsoft Docs [ ^ ]。


没有多大意义,但



Doesn't make a lot of sense, but

public interface ICommand<T1, T2>
{
    T1 PropA { get; set; }
    T2 PropB { get; set; }
}

public interface IBaseStuff
{
    int PropD { get; set; }
}

public interface IMyBaseStuff<T>
{
    T PropC { get; set; }
}

public class MyGenericCommand<T> : ICommand<T, T> where T : IMyBaseStuff<IBaseStuff>
{
    public T PropA { get; set; }
    public T PropB { get; set; }
}

public class BaseStuff : IBaseStuff
{
    public int PropD {get;set;}
}

public class MyCommandClass : IMyBaseStuff<IBaseStuff>
{
    public IBaseStuff PropC {get; set;}
}





使用





Usage

MyGenericCommand<MyCommandClass> _command = new MyGenericCommand<MyCommandClass>();
_command.PropA = new MyCommandClass();
_command.PropB = new MyCommandClass();

_command.PropA.PropC = new BaseStuff();
_command.PropA.PropC.PropD = 123;


这篇关于如何实例化泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆