C# 使用反射的C类型比较

C# 使用反射的C类型比较,c#,reflection,comparison,C#,Reflection,Comparison,我想使用反射检查属性是否为DbSet类型 public class Foo { public DbSet<Bar> Bars { get; set; } } 是否有其他方法检查propType是否为DbSet类型? 谢谢 代码的问题在于,它假设typeofDbType表示常规类型。它不是普通类型:而是泛型类型定义。这就是IsAssignableFrom、IsSubclassOf等不起作用的原因。如果以下条件为真,则类型x为DbSet类型: x.IsGenericType &

我想使用反射检查属性是否为DbSet类型

public class Foo
{
    public DbSet<Bar> Bars { get; set; }
}
是否有其他方法检查propType是否为DbSet类型? 谢谢


代码的问题在于,它假设typeofDbType表示常规类型。它不是普通类型:而是泛型类型定义。这就是IsAssignableFrom、IsSubclassOf等不起作用的原因。如果以下条件为真,则类型x为DbSet类型:

x.IsGenericType && x.GetGenericTypeDefinition() == typeof(DbSet<>) && x.GetGenericTypeArguments()[0] == typeof(T)

您是否也需要它来处理DbSet的子类?如果没有,您可以使用:

if (propType.IsGenericType &&
    propType.GetGenericTypeDefinition() == typeof(DbSet<>))
全样本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

class Test<T>
{
    public List<int> ListInt32 { get; set; }
    public List<T> ListT { get; set; }
    public string Other { get; set; }
    public Action<string> OtherGeneric { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var query = from prop in typeof(Test<string>).GetProperties()
                    let propType = prop.PropertyType
                    where propType.IsGenericType &&
                          propType.GetGenericTypeDefinition() == typeof(List<>)
                    select prop.Name;

        foreach (string name in query)
        {
            Console.WriteLine(name);
        }
    }
}

对于子类,您只需要在继承层次结构上递归地应用相同的测试。如果您需要测试接口,那就更麻烦了。

我建议下面的类型比较对我来说很好:

foreach (var prop in customObject.GetType().GetProperties().Where(e => e.CanRead && e.CanWrite))
{
    var typeName = prop.PropertyType.FullName ?? "";
    //!!! Type comparision here:
    if (typeName == typeof(string).FullName)
    {
        prop.SetValue(customObject, "abc");
        continue;
    }
    // other code
}
对于可为空的类型,例如DateTime?您可以使用这种类型的比较:

if (typeName.Contains(typeof(string).FullName))
{
    prop.SetValue(customObject, "abc");
}

你能使用PropertyInfo.PropertyType吗这里有一个指向MS的链接@DJKRAZE:PropertyInfo.PropertyType返回System.Data.Entity.DbSet'1[[Console1.Bar,…]谢谢。但是我找不到任何GetGenericTypeBase实例方法。你是说GetGenericTypeDefinition吗?@Kamyar抱歉,我是说GetGenericTypeDefinition已修复。
foreach (var prop in customObject.GetType().GetProperties().Where(e => e.CanRead && e.CanWrite))
{
    var typeName = prop.PropertyType.FullName ?? "";
    //!!! Type comparision here:
    if (typeName == typeof(string).FullName)
    {
        prop.SetValue(customObject, "abc");
        continue;
    }
    // other code
}
if (typeName.Contains(typeof(string).FullName))
{
    prop.SetValue(customObject, "abc");
}