简体   繁体   English

访问泛型对象的非泛型成员

[英]Accessing non-generic members of a generic object

Is there a way to collect (eg in a List) multiple 'generic' objects that don't share a common super class? 有没有办法收集(例如在List中)不共享一个共同超类的多个“通用”对象? If so, how can I access their common properties? 如果是这样,我如何访问他们的共同属性?

For example: 例如:

class MyObject<T>
{
   public T Value { get; set; }
   public string Name { get; set; }

   public MyObject(string name, T value)
   {
      Name = name;
      Value = value;
   }
}

var fst = new MyObject<int>("fst", 42);
var snd = new MyObject<bool>("snd", true);

List<MyObject<?>> list = new List<MyObject<?>>(){fst, snd};

foreach (MyObject<?> o in list)
   Console.WriteLine(o.Name);

Obviously, this is pseudo code, this doesn't work. 显然,这是伪代码,这不起作用。

Also I don't need to access the .Value property (since that wouldn't be type-safe). 此外,我不需要访问.Value属性(因为这不是类型安全的)。

EDIT: Now that I've been thinking about this, It would be possible to use sub-classes for this. 编辑:既然我一直在考虑这个问题,那么可以使用子类。 However, I think that would mean I'd have to write a new subclass for every new type. 但是,我认为这意味着我必须为每个新类型编写一个新的子类。


@ Grzenio Yes, that exactly answered my question. @ Grzenio是的,这完全回答了我的问题。 Of course, now I need to duplicate the entire shared interface, but that's not a big problem. 当然,现在我需要复制整个共享接口,但这不是一个大问题。 I should have thought of that... 我应该想到这个......

@ aku You are right about the duck typing. @ aku你对鸭子打字是正确的。 I wouldn't expect two completely random types of objects to be accessible. 我不希望可以访问两个完全随机类型的对象。

But I thought generic objects would share some kind of common interface, since they are exactly the same, apart from the type they are parametrized by. 但我认为通用对象会共享某种通用接口,因为它们完全相同,除了它们被参数化的类型。 Apparently, this is not the case automatically. 显然,情况并非如此。

I don't think it is possible in C#, because MyObject is not a baseclass of MyObject. 我认为在C#中不可能,因为MyObject不是MyObject的基类。 What I usually do is to define an interface (a 'normal' one, not generic) and make MyObject implement that interface, eg 我通常做的是定义一个接口(一个'普通',不通用),并让MyObject实现该接口,例如

interface INamedObject
{
    string Name {get;}
}

and then you can use the interface: 然后你可以使用界面:

List<INamedObject> list = new List<INamedObject>(){fst, snd};

foreach (INamedObject o in list)
   Console.WriteLine(o.Name);

Did it answer your question? 它回答了你的问题吗?

C# doesn't support duck typing. C#不支持鸭子打字。 You have 2 choices: interfaces and inheritance, otherwise you can't access similar properties of different types of objects. 您有两种选择:接口和继承,否则您无法访问不同类型对象的类似属性。

最好的方法是添加一个公共基类,否则你可以回到反射。

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

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