2011-01-28 56 views
2

的我得做一些一串代码像铸造OBJECTTYPE

if control == typeof(GridCurrencyTextBox)) 
{ 
    ((GridCurrencyTextBox)(_control)).Text = .... 
} 
if control == typeof(TextBox)) 
{ 
    ((TextBox)(_control)).Text = .... 
} 

等。 我知道我可以通过control.GetType()来估计类型,但是.Text属性只能在编译时知道类型。

我想是这样的:

Type t = _control.getType(); 
    (t(_control)).Text = ..... 

有什么建议?谢谢!

回答

3

很难从你的问题你实际上问说,但你尝试过:

ITextControl textControl = _control as ITextControl; 
if(textControl != null) 
{ 
    textControl.Text = //... 
} 

as铸造会给你(在这种情况下null)的默认值,如果对象你”重新尝试投射不是正确的类型,据我所知,.NET中的大多数(所有?)文本控件都来自ITextControl(它只定义了Text属性)。

这里假设你使用的是ASP.NET。正如其他人所提到的,在Windows Forms Control中有一个Text属性,因此您只需确保将其转换为Control,并且如果它已经是控件,则该检查是不必要的(除非要确保该值不为空)。

如果您使用任何其他类型的控件,并且它不是从一种可为您提供Text属性的常见类型派生出来的,那么您可能不得不诉诸于使用反射,但这远非理想,因为它会是慢:

PropertyInfo text = _control.GetType().GetProperty("Text", BindingFlags.Public | BindingFlags.Instance, null, typeof(string), Type.EmptyTypes, null); 
if(text != null) 
{ 
    text.SetValue(obj, /* some value */, null); 
} 
+0

是不是ITextControl只在ASP可用(因为它在System.Web.UI程序定义的接口命名空间)? – 2011-01-28 10:10:37

0

如果您使用的是.NET 3.0,你可以利用的扩展方法来重写你的代码也看起来更好一点。您的每一个对比组成的几个小步骤:​​

  1. 检查特定类型的
  2. 如果对象是特定类型的,施放它,它
  3. 执行一些动作

步骤1和2可以使用as运营商执行(因为您的目标必须是对象,因为as运算符只能投射引用类型)。第3步可以通过委托完成。因此,一个辅助函数看起来是这样的:

public static class Helper 
{ 
    public static void Do<T>(object obj, Action<T> action) 
     where T : class 
    { 
     T castedObject = obj as T; 
     if (castedObject != null && action != null) 
      action(castedObject); 
    } 
} 

然后,你可以拨打:

Helper.Do<TextBox>(control, delegate(TextBox obj) { obj.Text = "your text goes here"; }); 

...你必须处理每种类型。此解决方案使用助手类和匿名委托。

这不是最好的解决方案。随着扩展方法和lambda表达式,你可以有这样的:

public static class ObjectExtensions 
{ 
    public static void Do<T>(this T obj, Action<T> action) 
    { 
     if (obj != null && action != null) 
      action(obj); 
    } 

    public static T Cast<T>(this object obj) 
     where T : class 
    { 
     return obj as T; 
    } 
} 

...及用途:

control.Cast<TextBox>().Do(t => t.Text = "your text goes here"); 

你必须处理每种类型。这条线比以前的解决方案更具可读性。但在这种情况下,你必须知道扩展方法和lambda表达式是如何工作的。

0

如果你有财产,你不知道类型,你总是可以做到这一点:

var type = _control.GetType(); 
var propertyInfo = type.GetProperty("Text"); 
if(propertyInfo!=null) propertyInfo.SetValue(_control,"Some Value");