如何确定对象内是否有sbyte类型?

时间:2015-06-03 11:28:13

标签: c# c#-4.0

如何确定对象内是否存在sbyte类型?

void Do() {
   object obj = func();
   bool isSByte = obj.GetType() is sbyte; //not correct
}
object func() {
   object obj = new sbyte(-124);
   return obj;
}

1 个答案:

答案 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)