是否有可能使用C#泛型类型化的名单? [英] Is it possible to use a list of untyped generics in C#?

查看:106
本文介绍了是否有可能使用C#泛型类型化的名单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下面的设计没有成功:

I'm trying the following design without success:

abstract class Foo<T>
{
    abstract T Output { get; }
}

class Bar
{
    List<Foo> Foos;
}



我会不喜欢使用数组列表,因为我将不得不使用不安全的类型转换得到的类型。我想富被类型化,使输出不只是一个对象,在这种情况下,我不得不使用不安全的演员也是如此。

I would dislike using an array list, because I would have to use unsafe casts to get the type. I'd like Foo to be typed so that "Output" isn't just an object, in which case I'd have to use unsafe casts as well.

由于我的代码是在那一刻,我使用美孚无类型与输出作为一个对象。

As my code is at the moment, I use Foo untyped with Output as an object.

推荐答案

如果我理解正确的话,你希望列表物体在不同类型的输出的 S,对不对?由于这些输出是不同的类型,你将不得不使用反正这里投下

If I understand you correctly, you want a list of Foo objects which have different types of Outputs, right? Since these outputs are of different types, you would have to use casts here anyway.

但是,下面的想法可能会有所帮助。你怎么样声明一个叫非通用接口的IFoo :¹

However, the following idea might help. How about you declare a non-generic interface called IFoo: ¹

public interface IFoo
{
    object Output { get; }
}



,然后在你的抽象类实现:

and then implement it in your abstract class:

abstract class Foo<T> : IFoo
{
    abstract T Output { get; }
    object IFoo.Output { get { return Output; } }
}



然后,你可以声明列表的IFoo 取值:

class Bar
{
    List<IFoo> Foos;
}

当访问这些FOOS,您可以检索输出通过一个对象接口:

When accessing those foos, you can either retrieve the output as an object via the interface:

var myObject = Foos[0].Output;     // type ‘object’



或者你可以尝试去发现真正的类型,如果你知道,它可以只有一些特定类型之一:

or you can try to discover the real type if you know that it can only be one of a few specific types:

if (Foos[0] is Foo<string>)
    var myString = ((Foo<string>) Foos[0]).Output;   // type ‘string’

您甚至可以完全基于过滤的类型,例如:

You can even do filtering based on the type, for example:

// Type ‘IEnumerable<string>’ (rather than ‘IEnumerable<object>’)!
var stringFoos = Foos.OfType<Foo<string>>().Select(f => f.Output);



¹ <子>你也可以让这个所谓的抽象基类美孚< T> 从中获得。在这种情况下,你需要标记美孚< T> .OUTPUT 关键字,并使用 base.Output 访问抽象基成员。

¹ You can also make this an abstract base class called Foo and have Foo<T> derive from it. In that case, you would need to mark Foo<T>.Output with the new keyword and use base.Output to access the abstract base member.

这篇关于是否有可能使用C#泛型类型化的名单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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