简体   繁体   中英

Why is my C# IS statement not working?

I have the following code, where T is a generic defined as such:

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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