为什么我不能使用这段代码? [英] Why I cannot used this code?
本文介绍了为什么我不能使用这段代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 System.Collections.Generic;
命名空间 ConsoleApplication2
{
class Program
{
私有 静态 void Main( string [] args)
{
Dictionary< int,HandlerBase< TBaseClass,SBaseClass>> dictionary = new Dictionary< int,HandlerBase< TBaseClass,SBaseClass>>();
HandlerBase< TempT,TempS> temp = new TempHandler();
dictionary.Add( 1 ,temp);
}
}
class TBaseClass
{
}
class SBaseClass
{
}
class TempT:TBaseClass
{
}
class TempS :SBaseClass
{
}
class HandlerBase< T,S>
其中 T:TBaseClass
其中 S:SBaseClass
{
}
/// /////// //////////////////////////////
class TempHandler:HandlerBase< TempT,TempS>
{
public TempHandler(){}
}
}
我的尝试:
我'我试图采用通用T基类并在字典中使用它。
解决方案
HandlerBase< tbaseclass,>
与HandlerBase< tempt,>
不同,甚至TempT
继承TBaseClass
和TempS
继承SBaseClass
...
你应该定义字典要容纳HandlerBase< tempt,>
...
为了让你明白更多...
泛型实际上是一种泛型类型,它可以有不同的实际类型,但是当你实际创建一个实例时,那个实例不是通用的再...它有一个非常具体,定义良好的类型,内部继承不属于它(替换TBaseClass
和S BaseClass
用对象来更清楚地看到它)...
你所期望的,同一个泛型的不同实例表现得像一个来自另一个的继承对象 - 错误...
参见例如List< string>
和List< int>
...如果您遵循逻辑而不是List< string>
的任何成员可以转换为List<的成员; int>
,但这意味着,任何字符串
都可以转换为int
- 并且我们知道不是真的......
(缺少的线索是int和string都具有相同的基类)
[/ EDIT]
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
private static void Main(string[] args)
{
Dictionary<int, HandlerBase<TBaseClass, SBaseClass>> dictionary = new Dictionary<int, HandlerBase<TBaseClass, SBaseClass>>();
HandlerBase<TempT, TempS> temp = new TempHandler();
dictionary.Add(1, temp);
}
}
class TBaseClass
{
}
class SBaseClass
{
}
class TempT : TBaseClass
{
}
class TempS : SBaseClass
{
}
class HandlerBase<T, S>
where T : TBaseClass
where S : SBaseClass
{
}
////////////////////////////////////////
class TempHandler : HandlerBase<TempT, TempS>
{
public TempHandler() { }
}
}
What I have tried:
I'm trying to take a generic T base class and used it in dictionary.
解决方案
HandlerBase<tbaseclass,>
is not the same asHandlerBase<tempt,>
, evenTempT
inheritsTBaseClass
andTempS
inheritsSBaseClass
...
You should define dictionary to holdHandlerBase<tempt,>
...
[EDIT]
To make it clear more for you...
A generic is a actually a generic type, that can have different actual types, but the very moment you actually created an instance, that instance not generic anymore...it has a very specific, well defined type, and inner inheritance not part of it (replaceTBaseClass
andSBaseClass
with object to see it more clearly)...
What you have expected, that the different instances of the same generics behave like inherited object one from the other - wrong...
See for instanceList<string>
andList<int>
...If you follow your logic than any member ofList<string>
can be converted to a member ofList<int>
, but that means, that anystring
can be converted toint
- and that we know not to be true...
(The missing clue is that both int and string has the same base class)
[/EDIT]
这篇关于为什么我不能使用这段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文