c#中是否有类似的类型定义,或者以某种方式获得类似的行为?我在谷歌上搜了一下,但到处都是否定的。目前我的情况类似如下:

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型。如果能简化一下就好了……

编辑:ie。也许是对EventHandler进行类型定义,而不需要重新定义它来获得类似的行为。


当前回答

如果您知道自己在做什么,那么可以定义一个类,使用隐式操作符在别名类和实际类之间进行转换。

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 };
    }
}

我并不赞同这种方法,也从未使用过类似的方法,但这可能适用于某些特定的情况。

其他回答

在c# 10中,你可以这样做

global using Bar = Foo

它的工作方式类似于项目中的类型定义。

我还没有对它进行深入测试,所以可能会有一些怪癖。

我用它就像

global using DateTime = DontUseDateTime

其中DontUseDateTime是一个标记为Obsolete的结构体,以强制人们使用NodaTime。

如果您知道自己在做什么,那么可以定义一个类,使用隐式操作符在别名类和实际类之间进行转换。

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 };
    }
}

我并不赞同这种方法,也从未使用过类似的方法,但这可能适用于某些特定的情况。

我在c#中发现的typedef的最佳替代方法是使用。例如,我可以用下面的代码通过编译器标志来控制浮点精度:

#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif

不幸的是,它要求您将它放在使用real_t的每个文件的顶部。目前没有办法在c#中声明全局命名空间类型。

我会做

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

c#支持一些事件委托的继承协方差,所以像这样的方法:

void LowestCommonHander( object sender, EventArgs e ) { ... } 

可以用来订阅您的事件,没有显式强制转换所需

gcInt.MyEvent += LowestCommonHander;

你甚至可以使用lambda语法,智能感知将为你完成:

gcInt.MyEvent += (sender, e) =>
{
    e. //you'll get correct intellisense here
};