如何找出某个类型是否附加了字符串转换器?

时间:2010-09-29 13:25:46

标签: c# wpf typeconverter

问题在于:

我有某个特定对象的属性。此属性的类型为t。我需要找出,如果字符串值可以附加到此属性。

例如:我有一个Windows.Controls.Button的实例。我需要一个机制,它将为属性Button.Background返回true,但对Button.Template返回false。

有人可以帮忙吗?非常感谢

2 个答案:

答案 0 :(得分:1)

我认为你把问题带到了错误的方向:

该属性不直接接受String:如果存在转换器,实际上该属性将转换为良好类型。

然后,您可以查看是否存在使用此代码的转换器:

public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString)
{
   // Checks to see if the value passed is valid.
   return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))
            .IsValid(aString);
}

这些页面也可能让您感兴趣:

  1. http://msdn.microsoft.com/en-us/library/aa970913.aspx
  2. http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx

答案 1 :(得分:0)

public static bool PropertyCheck(this object o, string propertyName)
{
    if (string.IsNullOrEmpty(propertyName))
        return false;
    Type type = (o is Type) ? o as Type : o.GetType();

    PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty);

    if (pi != null && pi.PropertyType == typeof(string))
        return true;

    return false;
}

然后像这样调用它:

object someobj = new Object();
if (someobj.PropertyCheck("someproperty"))
     // do stuff

或者你可以这样做:

Type type = typeof(someobject);
if (type.PropertyCheck("someproperty"))

这有一些限制,因为您无法检查Type类型本身的属性,但如果需要,您可以随时创建另一个版本。

我认为这就是你想要的,希望有所帮助