0

次のように、コード ビハインドからユーザー コントロールのプロパティまたはメソッドを動的に追加します。

foreach (DataRow drModuleSettings in dsModuleSettings.Tables[0].Rows)
{
    if (!string.IsNullOrEmpty(dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString()))
        userControl.Title = dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString();
}

「userControl.Title」はサンプルです。実際には、次のようなコードに置き換える必要があります。

        userControl.drModuleSettings["SettingName"] = dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString();

問題は、これを行う方法がわからないことです。

誰か助けてください。

ありがとう!

4

2 に答える 2

1

Reflectionを使用する必要があります。

次のコードとリファレンスを見てください。

ここを参照してください:リフレクションを使用してオブジェクト プロパティを設定する

また、ここ: http://www.dotnetspider.com/resources/19232-Set-Property-value-dynamically-using-Reflection.aspx :

このコードは上記の参照からのものです。

// will load the assembly
Assembly myAssembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\MyClassLibrary.dll");

// get the class. Always give fully qualified name.
Type ReflectionObject = myAssembly.GetType("MyClassLibrary.ReflectionClass");

// create an instance of the class
object classObject = Activator.CreateInstance(ReflectionObject);

// set the property of Age to 10. last parameter null is for index. If you want to send any value for collection type
// then you can specify the index here. Here we are not using the collection. So we pass it as null
ReflectionObject.GetProperty("Age").SetValue(classObject, 10,null);

// get the value from the property Age which we set it in our previous example
object age = ReflectionObject.GetProperty("Age").GetValue(classObject,null);

// write the age.
Console.WriteLine(age.ToString());
于 2013-03-30T07:40:48.090 に答える
0

プロパティを使用できdynamicます。つまり、userControl.drModuleSettingsタイプは になりますdynamic

次に、実行時に値を割り当てることができます

userControl.drModuleSettings = new {SomeProperty = "foo", AnotherProperty = "bar"};

dynamic キーワードと DynamicObject の詳細については、こちらこちらをご覧ください。

注 - C# 4.0 以降が必要です。

于 2013-03-30T07:46:12.420 に答える