Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.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
C# 如何确定某个类型是否连接了字符串转换器?_C#_Wpf_Typeconverter - Fatal编程技术网

C# 如何确定某个类型是否连接了字符串转换器?

C# 如何确定某个类型是否连接了字符串转换器?,c#,wpf,typeconverter,C#,Wpf,Typeconverter,问题是: 我有一个特定对象的属性。此属性的类型为t。我需要找出是否可以将字符串值附加到此属性 例如:我有一个Windows.Controls.Button的实例。我需要一个机制,它将为property Button.Background返回true,但为Button.Template返回false 有人能帮忙吗?非常感谢 public static bool PropertyCheck(this object o, string propertyName) { if (string.Is

问题是:

我有一个特定对象的属性。此属性的类型为t。我需要找出是否可以将字符串值附加到此属性

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

有人能帮忙吗?非常感谢

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"))
或者你可以这样做:

object someobj = new Object();
if (someobj.PropertyCheck("someproperty"))
     // do stuff
Type type = typeof(someobject);
if (type.PropertyCheck("someproperty"))
这有一些限制,因为您无法检查
类型
类型本身的属性,但如果需要,您始终可以制作另一个版本


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

我想你把问题带错方向了:

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

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

public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString)
{
   // Checks to see if the value passed is valid.
   return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))
            .IsValid(aString);
}
您可能也会对这些页面感兴趣:


  • 按钮
    没有背景属性…你是说
    文本
    属性吗?好吧,忘了按钮吧-以网格为例。将字符串值“#00556677”传递给其背景属性时,它将转换为笔刷。但不能将某些字符串值传递给它的模板属性。这就是我需要了解的关于任何对象的任何属性的信息。本例为所有属性返回true,其类型为string。这不是我所需要的。我需要找出所有属性,它们的值可以在XAML中通过字符串设置。请参阅我在上一篇文章中给出的一个示例,其中包含背景和模板。无论如何,感谢您的反应非常感谢-这为我指明了一个很好的方向,尽管我需要的确切代码是:return TypeDescriptor.GetConverter(typeof(thetypeoftimedproperty)).CanConvertFrom(typeof(String));美好的玩得很开心:-)