【问题标题】:How To Change Property Value Which Was Get By Reflection C#如何更改通过反射 C# 获取的属性值
【发布时间】:2015-05-21 13:19:16
【问题描述】:

我有一个带有按钮类的 dll。它看起来像这样:

internal class CoolButton12345: UserControl
{
  all fields, properties and methods...
  public Image Image{get;set;}
}

我正在尝试将此按钮属性值更改为我自己的值。

dynamic playButton = typeof (FooDll).Assembly.GetType("ClassWhichHasThisButton")
                .GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
                .FirstOrDefault(x => x.Name == "playButton").GetValue(FooInstance.Controls[0]);
playButton.Image = (Image)pauseBitmap;

但是我收到了这个错误

未处理的类型异常 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' 发生在 System.Core.dll

为什么我的方法不对? 请告诉我我可以做这样的事情吗? 如果我可以请帮助找到如何做到这一点。

【问题讨论】:

    标签: c# .net dynamic reflection


    【解决方案1】:

    试试这个:

    dynamic playButton = FooInstance.playButton;
    
    playButton.Image = (Image)pauseBitmap;
    

    【讨论】:

    • 能否请您添加一些代码,我该怎么做?
    • 没关系,但我需要为playButton的Image属性设置值,而不是playButton。
    • 那么你需要reflect该对象的Image属性。
    • 我可以从 Controls 数组中获取实例。所以它有 UserControl 类型。
    • 我得到异常:“'System.Windows.Forms.UserControl' 不包含 'Image' 的定义”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2010-11-02
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多