要检查类型是否是C#中另一种类型的子类,很容易:
typeof (SubClass).IsSubclassOf(typeof (BaseClass)); // returns true
Run Code Online (Sandbox Code Playgroud)
但是,这将失败:
typeof (BaseClass).IsSubclassOf(typeof (BaseClass)); // returns false
Run Code Online (Sandbox Code Playgroud)
有没有办法检查类型是否是基类本身的子类OR,而不使用OR运算符或使用扩展方法?
我有一个包含以下事件的基类:
public event EventHandler Loading;
public event EventHandler Finished;
Run Code Online (Sandbox Code Playgroud)
在继承自此基类的类中,我尝试引发事件:
this.Loading(this, new EventHandler()); // All we care about is which object is loading.
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
事件'BaseClass.Loading'只能出现在+ =或 - =(BaseClass')的左侧
我假设我不能像其他继承的成员一样访问这些事件?
我正在尝试编写验证来检查Object实例是否可以转换为变量Type.我有一个Type实例,用于他们需要提供的对象类型.但类型可能会有所不同.这基本上就是我想要做的.
Object obj = new object();
Type typ = typeof(string); //just a sample, really typ is a variable
if(obj is typ) //this is wrong "is" does not work like this
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
类型对象本身具有IsSubClassOf和IsInstanceOfType方法.但我真正想要检查的是obj是typ的实例还是从typ派生的任何类.
看起来像一个简单的问题,但我似乎无法弄明白.
我正在尝试通过MassTransit发布的消息遇到基本类型问题.考虑以下:
[Serializable]
public abstract class Event : CorrelatedBy<Guid> {
public Guid CorrelationId { get; set; }
public abstract string EventName { get; }
public override string ToString() {
return string.Format("{0} - {1}", EventName, CorrelationId);
}
}
[Serializable]
public class PersonCreated : Event {
public PersonCreated(Guid personId, string firstName, string lastName) {
PersonId = personId;
FirstName = firstName;
LastName = lastName;
}
public readonly Guid PersonId;
public readonly string FirstName;
public readonly string LastName;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用以下内容发布抽象事件的集合时:
public void PublishEvents(IEnumerable<Event> events) { …Run Code Online (Sandbox Code Playgroud)