GetType()。具有泛型Type参数的Class中的名称

时间:2015-12-07 13:31:02

标签: c# generics

有没有办法在没有做一些String操作的情况下获取没有泛型类型参数计数的Typename?

在我的示例中,我需要 CreatedEvent 而不是 CreatedEvent`1

public class LogEvent<T> {

    public LogEvent (T logObj) {
        LogObject = logObj;
    }

    T LogObject { get; private set; }

    public string GetEventName () {
        return GetType().Name;
    }
}

public class CreatedEvent<T> : LogEvent<T> {
    public CreatedEvent(T logObj) : base (logObj) {} 
}

public class DeleteEvent : LogEvent<SomeObj> {
    public DeleteEvent(SomeObj logObj) : base (logObj) {}
}

// --
var created = new CreatedEvent<SomeObj>( exampleObj );
var deleted = new DeleteEvent( exampleObj );

// --

Console.WriteLine ( created.GetEventName() ); // CreatedEvent`1
Console.WriteLine ( deleted.GetEventName() ); // DeletedEvent 

0 个答案:

没有答案