在C#中的typedef等效 [英] Equivalent of typedef in C#

查看:803
本文介绍了在C#中的typedef等效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个typedef等效的C#,或好歹得到某种类似的行为吗?我做了一些google搜索,但到处看似乎是否定的。目前我有类似以下的情况:

Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:

class GenericClass<T> 
{
    public event EventHandler<EventData> MyEvent;
    public class EventData : EventArgs { /* snip */ }
    // ... snip
}

现在,它并不需要一个火箭科学家弄清楚,试图执行该事件的处理程序时,这会很快导致大量打字(道歉可怕的双关语)的。它最终会被这样的:

Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this:

GenericClass<int> gcInt = new GenericClass<int>;
gcInt.MyEvent += new EventHandler<GenericClass<int>.EventData>(gcInt_MyEvent);
// ...

private void gcInt_MyEvent(object sender, GenericClass<int>.EventData e)
{
    throw new NotImplementedException();
}

除了在我的情况,我已经使用一个复杂的类型,不只是一个int。这会是很好,如果它是可以简化这个有点...

Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little...

编辑:IE浏览器。也许typedefing,而不是需要重新定义它获得类似的行为的事件处理程序。

ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour.

推荐答案

没有,没有的typedef等价物。您可以在一个文件中,例如中使用using指令。

No, there's no equivalent of typedef. You can use using directives within one file, e.g.

using CustomerList = System.Collections.Generic.List<Customer>;

但只会影响该源文件。

but that will only impact that source file.

幸运的是,你给的例子确实的有一个固定 - 隐式方法组转换。您可以更改您的事件订阅行,只是:

Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:

gcInt.MyEvent += gcInt_MyEvent;

:)

这篇关于在C#中的typedef等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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