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

您将需要使用反射

看看下面的代码和参考:

请参阅此处:使用反射设置对象属性

另外,在这里: 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

You could use dynamic properties. Which would mean that, userControl.drModuleSettings will be of type dynamic.

You can then assign it a value at runtime like

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

More about dynamic keyword and DynamicObject here and here.

Note - Requires C# 4.0 or above.

于 2013-03-30T07:46:12.420 回答