C# 反射。设置 TableAdapter ConnectionString

C# Reflection. Set TableAdapter ConnectionString

我希望有人能帮助解决这个问题。我一直在尝试为 WinForm 创建一个新的基础 class。我想要做的是让这个基础 class 遍历它上面的所有表适配器并更新它们的连接字符串,而无需任何人向表单添加任何代码。他们只是将表格适配器放在表单上,​​不用担心连接字符串设置,因为它都在基础 class.

中处理

我遇到的问题是我的反射代码可以很好地找到 属性 但无法设置它。有人可以帮忙吗?

下面是代码(已更新)

public class cFormWS : Form
{
    public string ConnectionStringToUse { get; set; }

    public cFormWS()
    {
        Load += cFormWS_Load;
    }

    void cFormWS_Load(object sender, EventArgs e)
    {
        InitiliseTableAdapters();
    }

    private void InitiliseTableAdapters()
    {          
        var ListOfComponents = EnumerateComponents();

        foreach (var ItemComp in ListOfComponents)
        {
            if (ItemComp.ToString().ToLower().EndsWith("tableadapter"))
            {
                var ItemCompProps = ItemComp.GetType().GetRuntimeProperties();

                var TASQLConnection = ItemCompProps.FirstOrDefault(w => w.PropertyType == typeof(System.Data.SqlClient.SqlConnection));

                if (TASQLConnection != null)
                {
                    var property = typeof(System.Data.SqlClient.SqlConnection).GetProperty("ConnectionString");

                    // How do I set the value ?

                    string value = "some new connection string";

                    var ConvertedProperty = Convert.ChangeType(value, property.PropertyType);

                    // tried seting value.  not working "object does not match target type"
                    property.SetValue(TASQLConnection, ConvertedProperty, null);


                    //// tried using a method.  not working "object does not match target type"
                    //var m = property.SetMethod;
                    //ParameterInfo[] parameters = m.GetParameters();
                    //m.Invoke(m, parameters); // m.Invoke(this, parameters); // m.Invoke(ItemComp, parameters);
                }                      
            }                
        }
    }

    private IEnumerable<Component> EnumerateComponents()
    {
        return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
               where typeof(Component).IsAssignableFrom(field.FieldType)
               let component = (Component)field.GetValue(this)
               where component != null
               select component;
    }  

编辑:

当您执行 SetValue 时,您需要传入要设置 属性 的对象。

  • 在您的第一个示例代码中,您传入了 ItemComp:这是不正确的,因为 ConnectionStringSqlConnection 的 属性,后者是 属性 共 ItemComp
  • 在您编辑的问题(和我的原始答案)中,您输入了 TASqlConnection。然而,这不是对象,而是一个PropertyInfo基于对象
  • 正确的方法是从 ItemComp 对象中获取值并将其传递给:

property.SetValue(TASQLConnection.GetValue(ItemComp), ConvertedProperty, null);

原始(不正确)答案:

您正在尝试设置 ConnectionString 属性 ItemComp。 ConnectionString 不是 TableAdapter 的 属性,而是 SqlConnection 的 属性(它是 TableAdapter 的 属性)。

设置 属性 的正确方法是这样的:

property.SetValue(TASQLConnection, ConvertedProperty, null);