ASP.. NET, c#,如何动态识别用户控件的属性或方法并为其添加值

本文关键字:方法 属性 添加 控件 识别 何动态 NET ASP 动态 用户 | 更新日期: 2023-09-27 18:06:30

如果想从后面的代码中动态地添加用户控件的属性或方法,就像这样:

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();
}

"用户控件。"Title"是一个示例,实际上它应该被这样的代码替换:

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

问题是我不知道怎么做。

谁来帮帮我。

谢谢!

ASP.. NET, c#,如何动态识别用户控件的属性或方法并为其添加值

您需要使用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());

您可以使用dynamic属性。这就意味着,userControl.drModuleSettings的类型为dynamic

你可以在运行时给它赋一个值,比如

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

关于动态关键字和DynamicObject的更多信息。

注意-需要c# 4.0或以上版本