gpt4 book ai didi

c# - 测试类型是否实现了 INotifyPropertyChanged?

转载 作者:行者123 更新时间:2023-11-30 22:33:22 25 4
gpt4 key购买 nike

我在给定 Type 的字段和属性上循环,我想测试字段类型或属性 Type 是否实现了 INotifyPropertyChanged

也许这听起来很奇怪,但我会解析字段/属性,例如字符串、整数和其他类型,但我也有一些 ObservableCollection 和我定义的一些继承自 的自定义类型INotifyPropertyChanged.

因此,在我的代码中,我想根据字段或属性是否实现 INotifyPropertyChanged 的事实进行一些测试。

最佳答案

您可以使用 GetInterfaceGetInterfaces :

static bool SupportsINotifyPropertyChanged(this Type type)
{
return null != type.GetInterface(typeof(INotifyPropertyChanged).FullName);
// or
// return type.GetInterfaces().Any(x => x == typeof(INotifyPropertyChanged));
}

或者稍微更通用的方法:

static bool SupportsInterface<T>(this Type type)
{
if (!typeof(T).IsInterface) throw new InvalidOperationException();
return type != null && type.GetInterfaces().Any(x => x == typeof(T));
}

关于c# - 测试类型是否实现了 INotifyPropertyChanged?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8328506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com