在C#中的typedef等效

C#中是否有typedef等价物,或者有些类似的行为? 我做了一些谷歌搜索,但我看起来似乎是负面的。 目前我的情况类似于以下内容:

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

现在,火箭科学家并没有想到,当试图为该事件实施处理程序时,这可能会很快导致大量输入(为可怕的双关语表示歉意)。 它最终会是这样的:

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类型。 如果有可能简化这一点,它会很好......

编辑:即。 也许可以键入EventHandler而不需要重新定义它以获得类似的行为。


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

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

但那只会影响该源文件。 在C和C ++中,我的经验是, typedef通常用于广泛包含的.h文件中,因此可以在整个项目中使用单个typedef 。 这种能力在C#中不存在,因为C#中没有包含#include功能,它允许您将来自一个文件的using指令包含在另一个文件中。

幸运的是,您提供的示例确实有一个修复 - 隐式方法组转换。 您可以将您的活动订阅线更改为:

gcInt.MyEvent += gcInt_MyEvent;

:)


乔恩真的给了一个很好的解决方案,我不知道你能做到这一点!

有时我采取的是从班级继承并创建其构造函数。 例如

public class FooList : List<Foo> { ... }

不是最好的解决方案(除非你的程序集被其他人使用),但它是有效的。


如果你知道你在做什么,你可以使用隐式运算符来定义一个类,以在别名类和实际类之间进行转换。

class TypedefString // Example with a string "typedef"
{
    private string Value = "";
    public static implicit operator string(TypedefString ts)
    {
        return ((ts == null) ? null : ts.Value);
    }
    public static implicit operator TypedefString(string val)
    {
        return new TypedefString { Value = val };
    }
}

我实际上并不认可这一点,也没有使用过这样的东西,但这可能适用于某些特定的情况。

链接地址: http://www.djcxy.com/p/53261.html

上一篇: Equivalent of typedef in C#

下一篇: Does kotlin coroutines have async call with timer?