"参数表达类型' B'不能用于类型' System.Object'"的委托参数。

时间:2018-01-15 11:39:25

标签: c# reflection

我有一个对象,想要在所有" String"上调用一个函数。输入(递归)。例如:

        public class A : ILo
        {
            public string Prop1 { get; set; }
            public Guid Id { get; set; }
            public B BInfo { get; set; }
            public List<C> ListOfC { get; set; }
        }

        public class B : ILo
        {
            public string Prop2 { get; set; }
            public Guid Id { get; set; }
        }
        public class C : ILo
        {
            public string Prop3 { get; set; }
            public Guid Id { get; set; }
        }


--------------
    public T Translate<T>(T need) where T: class
    {
        if (need == null) return default(T);
        var t = need.GetType();
        var props = t.GetProperties();
        foreach (var propInfo in props)
        {
            if (propInfo.PropertyType == typeof(string))
            {
                ParameterExpression pe = Expression.Parameter(t);
                Expression propExp = Expression.Property(pe, propInfo);
                Expression<Func<T, string>> eFunc = Expression.Lambda<Func<T, string>>(propExp, pe);
                var locVal = DoTranslation(need, eFunc, ((ILo)need).GetId());

                propInfo.SetValue(need, locVal);
            }
            else if (propInfo.PropertyType.IsClass)
            {
                var temp = Convert.ChangeType(propInfo.GetValue(need), propInfo.PropertyType);
                Translate(temp);
            }
            else if (propInfo.PropertyType.IsArray)
            {
                // do Translate for all items
            }
        }
        return need;
    }

当我打电话给&#34; B&#34;时,翻译功能完美无缺。或&#34; C&#34;我打电话给#34; A&#34;但是当它想要调用A.BInfo时我得到一个错误(在&#34; Expression&gt; eFunc = Expression.Lambda&gt;(propExp,pe);&#34;)。

我的错误是: &#34;参数表达类型&#39; B&#39;不能用于类型&#39; System.Object&#39;&#34;

的委托参数

0 个答案:

没有答案