0

让我解释。我有一个要向其中添加各种 ASP.NET 控件的列表。然后我希望遍历列表并设置一个 CssClass,但并非每个控件都支持属性 CssClass。

我想做的是测试底层实例类型是否支持 CssClass 属性并设置它,但我不确定如何在设置属性之前进行转换,因为我不知道每个 Control 对象的类型。

我知道我可以使用 typeof 或 x.GetType(),但我不确定如何使用它们将控件转换回实例类型,以便测试然后设置属性。


其实我似乎已经解决了这个问题,所以我想我会在这里为其他人发布代码。

foreach (Control c in controlList) {
    PropertyInfo pi = c.GetType().GetProperty("CssClass");
    if (pi != null) pi.SetValue(c, "desired_css_class", null);
}

我希望这对其他人有所帮助,因为我花了几个小时来研究这两行代码。

干杯

史蒂夫

4

2 回答 2

0

You may want to think about re-designing these classes making them implement an interface ICssControl or something along the lines which provides the CssClass property.

interface ICssControl

{ string CssClass { get; set;} }

You can then implement your logic as:

string desiredCssClass = "desired_css_class";
foreach (var control in controlList)
{
    var cssObj = control as ICssControl;
    if (cssObj != null)
        cssObj.CssClass = desiredCssClass;
}

This gets you away from needing to use reflection at all and should make for easier refactoring later on.

Edit

On re-reading you question, maybe you already have this interface and are asking how to cast it back to that interface?

于 2009-11-05T00:59:49.260 回答
0

Just to follow Preet's advice I have also posted this as an answer.

foreach (Control c in controlList) {
    PropertyInfo pi = c.GetType().GetProperty("CssClass");
    if (pi != null) pi.SetValue(c, "desired_css_class", null);
}

I hope that this helps someone in the future (probably me when I google it again).

于 2009-11-05T00:17:28.140 回答