【问题标题】:Reflection within properties?属性内的反射?
【发布时间】:2013-10-17 01:41:13
【问题描述】:

以下是我目前的情况......

public string Zip { get { return this.GetValue<string>("Zip"); } set { this.SetValue("Zip", value); } }

我想使用反射使这个动态化。 如,将属性的类型和名称传递给方法。我不确定如何去做,或者是否有可能。感谢您的帮助。

编辑:感谢 KooKiz,我能够更进一步,但仍然不是 100%。

public string Zip { get { return this.GetValue<string>(); } set { this.SetValue(value); } }

【问题讨论】:

  • 未问的问题:你为什么要这样做?如果您要定义很多这样的属性,那就是代码生成的目的。 T4 包含在 VS 中。
  • 如果您使用的是 .NET 4.5,您可能需要查看 CallerMemberName 属性:msdn.microsoft.com/en-us/library/…
  • @KooKiz 相当漂亮。这看起来很方便记录。
  • 在实现INotifyPropertyChanged 时经常会遇到类似的问题,并且经常建议将rewriting he assembly after it has been built 作为解决方案。它也应该在这里工作:写public string Zip { get; set; },C# 编译器创建的东西不能按照你想要的方式工作,后处理器将它重写为你想要的工作方式。

标签: c# dynamic reflection properties


【解决方案1】:

您可以稍微澄清一下您的问题。这对我来说太模糊了。

你在找这个吗?

public object DoSomething(Type type, string propertyName)
{
     var somethingWithProperty = Activator.CreateInstance(type, null);
     foreach (PropertyInfo property in somethingWithProperty.GetType().GetProperties())
     {
        if (property.Name == propertyName)
        {
            return property.GetValue(somethingWithProperty, null);
        }
     }

    throw new ArgumentException(string.Format("No property was found was found with this on [{0}] with propertyname [{1}]", type, propertyName));
}

还是这个?

    public object DoSomething(Func<object> propertyStuff)
    {
        return propertyStuff();
    }

用法:

public void FinallyIDoSomethingWithThatSomething()
{
    // first version
    DoSomething(typeof(StrangeOtherClass), "MyLittleProperty");

    // second version
    DoSomething(() => new StrangeOtherClass().MyLittleProperty);
    DoSomething(() => MyPropertyInMyOwnClass);
}

由于代码美化器显示错误的属性颜色,我将提供它们:

public string MyPropertyInMyOwnClass { get { return "Yay or nay."; } }

请注意,第二个版本更重构友好在第一个版本中当你重构StrangeOtherClass并重命名MyLittleProperty时,你的代码将在运行时中断,因为您很容易忘记重写函数的字符串参数。对于其他版本,至少编译器会为您提供错误。

如果您提供更多信息,我可以写更具体的答案。

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 2010-11-21
    • 2017-05-14
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    相关资源
    最近更新 更多