【问题标题】:How can I set targetPi? I think definition is not right but I don't know how can I fix this?如何设置 targetPi?我认为定义不正确,但我不知道如何解决这个问题?
【发布时间】:2013-08-01 14:14:25
【问题描述】:

//这里有一些代码

    object target = Activator.CreateInstance(typeof(T));   

    PropertyInfo[] sourceProperties = sourceType.GetProperties();

    foreach (PropertyInfo pi in sourceProperties)
    {
         PropertyInfo targetPi = typeof(T).GetProperty(pi.Name); //returns null why?

         object piValue = pi.GetValue(source, null);

         try
         {
               if (targetPi != null)   // it doesnt work 
               {
                    targetPi.SetValue(target,piValue, null); // target has typeof(T)
               }
         }
         catch { }         
    }
    return(T)target;
}

【问题讨论】:

  • 你没有告诉我们你想要达到的目标。您刚刚发布了格式错误的代码,仅此而已。请看tinyurl.com/so-hints

标签: c# reflection settings propertyinfo


【解决方案1】:

这对我有用:

struct Item1 { public double Foo { get; set; } }
struct Item2 { public double Foo { get; set; } }

class Program
{
    static void Main(string[] args)
    {
        Item1 i1 = new Item1();
        CopyDynamically(new Item2 { Foo = 42 }, ref i1);

        Console.WriteLine(i1.Foo);


        i1 = CopyDynamically<Item1>(new Item2 { Foo = 3.14 });

        Console.WriteLine(i1.Foo);
    }

    static void CopyDynamically<T>(object source, ref T target)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (target == null)
            throw new ArgumentNullException("target");

        foreach (PropertyInfo pi in source.GetType().GetProperties())
        {
            PropertyInfo targetPi = typeof(T).GetProperty(pi.Name);

            if (targetPi != null && targetPi.SetMethod != null && targetPi.SetMethod.IsPublic)
            {
                object val = pi.GetValue(source, null);
                object o = target;

                try { targetPi.SetValue(o, val, null); }
                catch { }

                target = (T)o;
            }
        }
    }
    static T CopyDynamically<T>(object source, params object[] ctorArgs)
    {
        T target = (T)Activator.CreateInstance(typeof(T), ctorArgs);

        CopyDynamically(source, ref target);

        return target;
    }
}

【讨论】:

  • 实际上,我一直在尝试将表映射到表,我弄清楚了,错误出在我的代码背景上。(表变量名称错误)。感谢您的帮助 mtman。还有任何人有问题可以问我:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 2023-02-03
  • 1970-01-01
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多