如何确定对象内是否存在sbyte类型?
void Do() {
object obj = func();
bool isSByte = obj.GetType() is sbyte; //not correct
}
object func() {
object obj = new sbyte(-124);
return obj;
}
答案 0 :(得分:4)
是(此变体更可取)
bool isSByte = obj is sbyte;
的GetType
bool isSByte = obj.GetType() == typeof(sbyte);
检查继承:
// sbyte
bool isInherits = typeof(sbyte).IsAssignableFrom(obj.GetType()); // true
// for classes
bool isMemoryStreamInheritsStream = typeof(Stream).IsAssignableFrom(typeof(MemoryStream)); // true (MemoryStream based on Stream)