【问题标题】:base type equality check fails基本类型相等检查失败
【发布时间】:2013-02-25 08:05:22
【问题描述】:

偶然发现了这个。这是我的场景:

|--> BaseTypeLibrary  (contains ViewModelBase)
|--> ModelLibrary     (contains Model)
|--> Business Library (contains equality check)

 public class Model : ViewModelBase{ }

 // returns false
 bool isViewModel = (type.IsAssignableFrom(typeof(ViewModelBase)));

首先,我确保 UI 库和 ModelLibrary 的引用指向同一个 BaseTypeLibrary。这是我执行的一些检查。

 // false
 Console.WriteLine(type.IsAssignableFrom(typeof(ViewModelBase)));

 // true
 Console.WriteLine((type.BaseType == typeof(ViewModelBase)));

 // true
 Console.WriteLine((typeof(ViewModelBase).Module.FullyQualifiedName) == (type.BaseType.Module.FullyQualifiedName));

 //true
 Console.WriteLine(type.IsSubclassOf(typeof(ViewModelBase)));

谁能解释为什么 IsAssignableFrom 会失败?

【问题讨论】:

  • 如何获得type

标签: c# .net inheritance reflection types


【解决方案1】:

当人们第一次使用IsAssignableFrom 时,这是一个很常见的问题。

在您的示例中,您需要在执行检查时反转实例和参数:

bool isViewModel = typeof(ViewModelBase).IsAssignableFrom(type);

来自MSDN

public virtual bool IsAssignableFrom(Type c)

返回值类型:System.Boolean

如果 c 和当前 Type 表示相同的类型,则为 true, 或者如果当前类型在 c 的继承层次中,或者如果 current Type 是 c 实现的接口,或者如果 c 是泛型 type 参数和当前 Type 表示约束之一 c.如果这些条件都不为真,或者 c 为空,则为假。

因此,您需要在候选基/接口类型上调用方法,并使用候选具体/子类型作为方法参数。 p>

我同意该方法的命名方式有些模棱两可。

【讨论】:

  • 虽然很明显...ModelViewModelBase,但反之则不然...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2018-06-30
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 2021-02-28
  • 1970-01-01
相关资源
最近更新 更多