简体   繁体   English

动态设置泛型类型参数

[英]Dynamically set generic type argument

Following on from my question here , I'm trying to create a generic value equality comparer. 从我的问题继在这里 ,我试图创建一个通用的价值相等比较。 I've never played with reflection before so not sure if I'm on the right track, but anyway I've got this idea so far: 我之前从未玩过反射,所以不确定我是否在正确的轨道上,但无论如何我到目前为止都有这个想法:

bool ContainSameValues<T>(T t1, T t2)
{
    if (t1 is ValueType || t1 is string)
    {
        return t1.Equals(t2);
    }

    else 
    {
        IEnumerable<PropertyInfo> properties = t1.GetType().GetProperties().Where(p => p.CanRead);
        foreach (var property in properties)
        {
            var p1 = property.GetValue(t1, null);
            var p2 = property.GetValue(t2, null);

            if( !ContainSameValues<p1.GetType()>(p1, p2) )
                return false;
        }
    }
    return true;
}

This doesn't compile because I can't work out how to set the type of T in the recursive call. 这不编译,因为我无法弄清楚如何在递归调用中设置T的类型。 Is it possible to do this dynamically at all? 是否可以动态执行此操作?

There are a couple of related questions on here which I have read but I couldn't follow them enough to work out how they might apply in my situation. 这里有几个相关的问题,我已经阅读了但是我无法完全了解它们如何适用于我的情况。

You can avoid reflection on invocation if you are happy to compare based on the statically know types of the properties. 如果您乐意根据静态知道的属性类型进行比较,则可以避免反映调用。

This relies on Expressions in 3.5 to do the one off reflection in a simple manner, it is possible to do this better to reduce effort for extremely nested types but this should be fine for most needs. 这依赖于3.5中的表达式以简单的方式进行一次性反射,可以更好地做到这一点,以减少极端嵌套类型的工作量,但这应该适合大多数需求。

If you must work off the runtime types some level of reflection will be required (though this would be cheap if you again cache the per property access and comparison methods) but this is inherently much more complex since the runtime types on sub properties may not match so, for full generality you would have to consider rules like the following: 如果必须解决运行时类型,则需要一定程度的反射(尽管如果再次缓存每个属性访问和比较方法,这会很便宜),但这本身就要复杂得多,因为子属性上的运行时类型可能不匹配所以,为了完全普遍,你必须考虑以下规则:

  • consider mismatched types to NOT be equal 认为不匹配的类型不相等
    • simple to understand and easy to implement 简单易懂,易于实施
    • not likely to be a useful operation 不太可能是一个有用的操作
  • At the point the types diverge use the standard EqualityComparer<T>.Default implementation on the two and recurse no further 在类型分歧的点上使用标准的EqualityComparer<T>.Default实现两者并且不再进一步递归
    • again simple, somewhat harder to implement. 实施起来更简单,更难实施。
  • consider equal if they have a common subset of properties which are themselves equal 如果它们具有本身相同的共同属性子集,则认为是相等的
    • complicated, not really terribly meaningful 复杂,不是非常有意义
  • consider equal if they share the same subset of properties (based on name and type) which are themselves equal 如果它们共享相同的属性子集(基于名称和类型),则认为它们是相等的
    • complicated, heading into Duck Typing 复杂,进入鸭子打字

There are a variety of other options but this should be food for thought as to why full runtime analysis is hard. 还有其他各种选择,但这应该是思考为什么完整的运行时分析很困难。

(note that I have changed you 'leaf' termination guard to be what I consider to be superior, if you want to just use sting/value type for some reason feel free) (请注意,我已经改变了你''叶子'终止守卫是我认为优越的,如果你想因某种原因只使用刺痛/价值类型而感到自由)

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


class StaticPropertyTypeRecursiveEquality<T>
{
    private static readonly Func<T,T, bool> actualEquals;

    static StaticPropertyTypeRecursiveEquality()
    {
        if (typeof(IEquatable<T>).IsAssignableFrom(typeof(T)) || 
            typeof(T).IsValueType ||
            typeof(T).Equals(typeof(object)))
        {
            actualEquals = 
                (t1,t2) => EqualityComparer<T>.Default.Equals(t1, t2);
        }
        else 
        {
            List<Func<T,T,bool>> recursionList = new List<Func<T,T,bool>>();
            var getterGeneric = 
                typeof(StaticPropertyTypeRecursiveEquality<T>)
                    .GetMethod("MakePropertyGetter", 
                        BindingFlags.NonPublic | BindingFlags.Static);
            IEnumerable<PropertyInfo> properties = typeof(T)
                .GetProperties()
                .Where(p => p.CanRead);
            foreach (var property in properties)                
            {
                var specific = getterGeneric
                    .MakeGenericMethod(property.PropertyType);
                var parameter = Expression.Parameter(typeof(T), "t");
                var getterExpression = Expression.Lambda(
                    Expression.MakeMemberAccess(parameter, property),
                    parameter);
                recursionList.Add((Func<T,T,bool>)specific.Invoke(
                    null, 
                    new object[] { getterExpression }));                    
            }
            actualEquals = (t1,t2) =>
                {
                    foreach (var p in recursionList)
                    {
                        if (t1 == null && t2 == null)
                            return true;
                        if (t1 == null || t2 == null)
                            return false;
                        if (!p(t1,t2))
                            return false;                            
                    }
                    return true;
                };
        }
    }

    private static Func<T,T,bool> MakePropertyGetter<TProperty>(
        Expression<Func<T,TProperty>> getValueExpression)
    {
        var getValue = getValueExpression.Compile();
        return (t1,t2) =>
            {
                return StaticPropertyTypeRecursiveEquality<TProperty>
                    .Equals(getValue(t1), getValue(t2));
            };
    }

    public static bool Equals(T t1, T t2)
    {
        return actualEquals(t1,t2);
    }
}

for testing I used the following: 为了测试,我使用了以下内容:

public class Foo
{
    public int A { get; set; }
    public int B { get; set; }
}

public class Loop
{
    public int A { get; set; }
    public Loop B { get; set; }
}

public class Test
{
    static void Main(string[] args)
    {
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<String>.Equals(
            "foo", "bar"));
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<Foo>.Equals(
            new Foo() { A = 1, B = 2  },
            new Foo() { A = 1, B = 2 }));
        Console.WriteLine(StaticPropertyTypeRecursiveEquality<Loop>.Equals(
            new Loop() { A = 1, B = new Loop() { A = 3 } },
            new Loop() { A = 1, B = new Loop() { A = 3 } }));
        Console.ReadLine();
    }
}

You need to call the method using reflection, like this: 你需要使用反射调用方法,如下所示:

MethodInfo genericMethod = typeof(SomeClass).GetMethod("ContainSameValues");
MethodInfo specificMethod = genericMethod.MakeGenericMethod(p1.GetType());
if (!(bool)specificMethod.Invoke(this, new object[] { p1, p2 }))

However, your method should not be generic in the first place; 但是,您的方法首先不应该是通用的; it should simply take two object parameters. 它应该只需要两个object参数。 (Or, if it is generic, it should cache properties and delegates in a generic type) (或者,如果它是通用的,它应该以泛型类型缓存属性和委托)

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

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