C#泛型不会允许代理类型约束 [英] C# Generics won't allow Delegate Type Constraints

查看:117
本文介绍了C#泛型不会允许代理类型约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时可以定义在C#中的一类,这样

Is it possible to define a class in C# such that

class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate

我不能为我的生活在.NET 3.5做到这一点,昨晚。我试图用

I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using

委托,代表,动作&LT; T&GT;和Func键&LT; T,T&GT;

在我看来,这应该是在某种程度上允许的。我想实现我自己的EventQueue。

It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.

最后我只是在做这个[原始近似提醒您。

I ended up just doing this [primitive approximation mind you].

internal delegate void DWork();

class EventQueue {
    private Queue<DWork> eventq;
}

但后来我失去了重用为不同类型的功能相同的定义的能力。

But then I lose the ability to reuse the same definition for different types of functions.

思考?

推荐答案

若干类是不可用作为一般约束上 - 枚举是另一个

A number of classes are unavailable as generic contraints - Enum being another.

有关代表,你可以得到的最接近的是:班,可能使用反射来检查(例如,在静态构造函数)的T的的委托:

For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T is a delegate:

    static GenericCollection()
    {
        if (!typeof(T).IsSubclassOf(typeof(Delegate)))
        {
            throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
        }
    }

这篇关于C#泛型不会允许代理类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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