gpt4 book ai didi

c# - 使用反射获取组件

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:40 27 4
gpt4 key购买 nike

我正在尝试使用反射获取表单的 BindingSource。以下代码是我到目前为止尝试过的代码,尽管它有错误:

public class MyClass :Form
{
BindingSource bs = new BindingSource();
}

public static class Class2
{
public static BindingSource GetBindingSource(string FieldNameP, Form FormP)
{
BindingSource Bs = null;

var info=FormP.GetType().GetField(FieldNameP);
if(info != null)
{
Bs = (BindingSource)info.GetValue(null)
}

return Bs;
}
}

最佳答案

在调用获取字段时,您需要使用 overload接受 binding flags .您可能需要反复试验一下,但我认为您需要:

BindingFlags.NonPublic | BindingFlags.Instance

.GetValue 获取您要在其上调用字段的对象的实例。

.GetValue(myform);

更好的方法可能是创建一个接口(interface):

public interface IBindable
{
BindingSource Source { get; }
}

将其应用于表单:

public class MyClass : Form, IBindable
{
private BindingSource _Source = new BindingSource();
public BindingSource Source { get { return _Source; } }
}

使用接口(interface):

BindingSource formSource = MyForm.Source;

关于c# - 使用反射获取组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com