我希望有人可以幫助這個。我一直在試圖爲WinForm創建一個新的基類。我想要做的是讓這個基類遍歷它所具有的所有表適配器,並更新它們的連接字符串,而不需要任何人向表單添加任何代碼。他們只是將表適配器放在表單上,不用擔心連接字符串設置,因爲它全部在基類中處理。C#反射。 Set TableAdapter ConnectionString
我遇到的問題是我的反射代碼可以找到屬性,但無法設置它。有人可以幫忙嗎?
下面是代碼(更新)
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;
}
你不需要反射這裏(或者你的代碼不會使其預期用途的任何意義)。 – leppie
據我所知,沒有其他辦法可以自動完成我想要的任務。 –
只有在TableAdapter不共享公共基類時纔會出現這種情況。可以? MSDN對此很模糊。 – leppie