Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ASP.NET,C#,如何动态标识用户控件的属性或方法并为其添加值?_C#_Asp.net_Properties_User Controls_Code Behind - Fatal编程技术网

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

ASP.NET,C#,如何动态标识用户控件的属性或方法并为其添加值?,c#,asp.net,properties,user-controls,code-behind,C#,Asp.net,Properties,User Controls,Code Behind,在中,您希望通过代码隐藏动态添加用户控件的属性或方法,如下所示: foreach (DataRow drModuleSettings in dsModuleSettings.Tables[0].Rows) { if (!string.IsNullOrEmpty(dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString())) userControl.Title = dsModuleSettings.Tables

在中,您希望通过代码隐藏动态添加用户控件的属性或方法,如下所示:

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();
问题是我不知道怎么做

请有人帮帮我


谢谢

您需要使用反射

请查看以下代码和参考:

请看这里:

还有,这里::

此代码来自上述参考:

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

您可以使用
动态
属性。这意味着,
userControl.drModuleSettings
将属于
动态类型

然后可以在运行时为其指定一个值,如

userControl.drModuleSettings = new {SomeProperty = "foo", AnotherProperty = "bar"};
有关dynamic关键字和DynamicObject以及的详细信息


注意-需要C#4.0或更高版本。

是否要求在运行时设置未知属性?这些属性不是未知的。它们保存在数据库中,并显示在dsModuleSettings中。如何知道控件是否具有这些属性?它们在另一个表中预定义,用户只能设置它们的值。不幸的是,我使用C#3.5。还有其他选择吗?那么我想反思是你的朋友,很高兴你用它找到了答案:)万分感谢!我从你建议的推荐人那里得到了答案()