C# Problem with type cast
here's the code,
Type tbn = Type.GetType(dii.DictionaryName)开发者_如何转开发;
DictionaryXmlInfo4BaseDictionary<tbn>.AddDictionaryXmlInfo((message));//error
You can't use generics like that. Generics are meant to be used for types known at compile time.
You can do it with reflection - getting the generic DictionaryXmlInfo4BaseDictionary
type definition, creating the closed type using Type.MakeGenericType
, then calling AddDictionaryXmlInfo
on it again by reflection... but it's relatively painful.
You cannot use generics with a type that is known only at runtime. The DictionaryXmlInfo4BaseDictionary<T>
type is generic and requires the T
argument to be known at compile time if you want to use it.
You can't use an instance of a type as a generic parameter.
The generic parameter should be the whatever the base instance is, DictionaryXmlInfo4BaseDictionary<object>
in the most generic case, but you probably want something further down the class hierarchy than that.
You can't use Type
in that way, refactor DictionaryXmlInfo4BaseDictionary
so it takes a Type paramater as part of the method e.g.
DictionaryXmlInfo4BaseDictionary.AddDictionaryXmlInfo(tbn, message);
精彩评论