Equivalent of typedef in C#

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

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...

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


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

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

but that will only impact that source file. In C and C++, my experience is that typedef is usually used within .h files which are included widely - so a single typedef can be used over a whole project. That ability does not exist in C#, because there's no #include functionality in C# that would allow you to include the using directives from one file in another.

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;

:)


Jon really gave a nice solution, I didn't know you could do that!

At times what I resorted to was inheriting from the class and creating its constructors. Eg

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

Not the best solution (unless your assembly gets used by other people), but it works.


If you know what you're doing, you can define a class with implicit operators to convert between the alias class and the actual class.

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

I don't actually endorse this and haven't ever used something like this, but this could probably work for some specific circumstances.

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

上一篇: NSString属性:复制或保留?

下一篇: 在C#中的typedef等效