简体   繁体   English

为什么我的C#IS语句不起作用?

[英]Why is my C# IS statement not working?

I have the following code, where T is a generic defined as such: 我有以下代码,其中T是通用定义如下:

public abstract class RepositoryBase<T> where T : class, IDataModel

This code works just fine: 这段代码工作得很好:

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType.FullName == typeof(T).FullName)  <--- Works just fine

vs this code which evaluates to false vs这个评估为false的代码

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType is T) <-- does not work

What am I doing wrong here? 我在这做错了什么?

is uses type comparison between the two objects. 在两个对象之间使用类型比较。 So DeclaringType is of type Type and typeof(T) is of type T , which are not equal. 因此DeclaringType的类型为Typetypeof(T)的类型为T ,它们不相等。

var aType = typeof(propertyInfo.DeclaringType);
var bType = typeof(T);
bool areEqual = aType is bType; // Always false, unless T is Type

What you are looking for is 你在寻找什么

TypeIsAssignableFrom TypeIsAssignableFrom

if (propertyInfo.DeclaringType.IsAssignableFrom(typeof(T)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM