[英]C# Reflection. Set TableAdapter ConnectionString
我希望有人可以对此提供帮助。 我一直在尝试为WinForm创建一个新的基类。 我想做的是让该基类遍历它所具有的所有tableadapters并更新其连接字符串,而无需任何人向该表单添加任何代码。 他们只是将tableadapters放在窗体上,而不必担心连接字符串设置,因为它们都是在基类中处理的。
我遇到的问题是我的反射代码可以找到合适的属性,但是无法设置它。 有人可以帮忙吗?
下面是代码(已更新)
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
:这是不正确的,因为ConnectionString
是SqlConnection
的属性,而SqlConnection
是ItemComp
的属性 TASqlConnection
。 但是,这不是对象,而是基于对象的PropertyInfo
ItemComp
对象获取值并将其传递给: property.SetValue(TASQLConnection.GetValue(ItemComp), ConvertedProperty, null);
原始(错误)答案:
您正在尝试设置ItemComp
的ConnectionString
属性。 ConnectionString不是TableAdapter
的属性,而是SqlConnection
的属性(这是TableAdapter
的属性)。
设置属性的正确方法是:
property.SetValue(TASQLConnection, ConvertedProperty, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.