简体   繁体   English

如何将对象转换为仅知道类名称的类?

[英]How to cast object to a class knowing only the class name?

I am a C# NewBie and I'm in a situation where i know the type of the object (ClassName) in 我是C#NewBie,并且处于某种情况下,我知道其中的对象(ClassName)的类型

ObservableCollection<ClassName>

and now i need to use it to cast returning object of the same thats comes as an 现在我需要使用它来投射返回的相同对象

ObservableCollection<object>

how do i do somethign like 我该怎么做

ObservableCollection<type> where type s the Type of ClassName? ObservableCollection<type>其中type是ClassName的类型? is it possible when i have the type of the ClassName i can use it instead of the ClassName if not how do i achive it? 如果我具有ClassName的类型,是否可以使用它而不是ClassName?

Generic parameters on concrete classes are never co-variant. 具体类的泛型参数从不协变。 And on interface they can only be variant if they are either used as input or output parameter, but never both. 并且在接口上,仅当它们用作输入或输出参数时,它们才可以是变量,但不能同时用作两者。

So you can't ever cast ObservableCollection<T> to ObservableCollection<object> . 因此,您无法将ObservableCollection<T> ObservableCollection<object>ObservableCollection<object>

Check out Covariance and Contravariance in Generics 在泛型中检查协方差和协方差

I'm a bit confused by your wording, do you mean you want: 您的措辞让我有些困惑,您是说要吗:

typeof(ClassName)

?

尝试这个:

return new ObservableCollection<object>(myClassNameObservableCollection);

From the last sentence of your question I guess you need that 从您问题的最后一句话,我想您需要

Type.MakeGenericType Type.MakeGenericType

So you can do something like that: 因此,您可以执行以下操作:

Type generic = typeof(ObservableCollection<>);
Type[] typeArgs = { typeof(ClassName) };
Type constructed = generic.MakeGenericType(typeArgs);
var obj = Activator.CreateInstance(constructed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM