IsAssignableFrom 和“is”的使用C# 中的关键字

发布于 2024-09-05 06:23:28 字数 854 浏览 2 评论 0原文

在尝试学习Unity,我不断看到以下在 MVC 中重写 GetControllerInstance 的代码:

if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }

在我看来,这是一种相当复杂的基本编写方式,

if(controllerType is IController) { ... }

我很欣赏那里isIsAssignableFrom 之间存在细微差别,即 IsAssignableFrom 不包括强制转换,但我很难理解这种差异的含义在实际场景中。

什么时候选择 IsAssignableFrom 而不是 is 很重要?它在 GetControllerExample 中会有什么不同?

if (!typeof(IController).IsAssignableFrom(controllerType))
      throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;

While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC:

if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }

this seems to me a pretty convoluted way of basically writing

if(controllerType is IController) { ... }

I appreciate there are subtle differences between is and IsAssignableFrom, ie IsAssignableFrom doesn't include cast conversions, but I'm struggling to understand the implication of this difference in practical scenarios.

When is it imporantant to choose IsAssignableFrom over is? What difference would it make in the GetControllerExample?

if (!typeof(IController).IsAssignableFrom(controllerType))
      throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

夏见 2024-09-12 06:23:28

这不一样。

if(controllerType is IController)

总是评估为false,因为controllerType始终是Type,并且是Type从来都不是IController

is 运算符用于检查实例是否与给定类型兼容。

IsAssignableFrom 方法用于检查类型是否与给定类型兼容。

It's not the same.

if(controllerType is IController)

would always evaluate to false since controllerType is always a Type, and a Type is never an IController.

The is operator is used to check whether an instance is compatible to a given type.

The IsAssignableFrom method is used to check whether a Type is compatible with a given type.

因为看清所以看轻 2024-09-12 06:23:28

typeof(IController).IsAssignableFrom(controllerType) 针对接口测试 Typeis 运算符针对接口测试实例。

typeof(IController).IsAssignableFrom(controllerType) tests a Type against the interface. The is operator tests an instance against the interface.

我一直都在从未离去 2024-09-12 06:23:28

is 关键字仅适用于实例,而 Type.IsAssignableFrom() 仅适用于类型。

is 的示例

string str = "hello world";
if(str is String)
{
    //str instance is of type String
}

请注意,str 是一个实例,而不是类型。

IsAssignableFrom() 的示例

string str = "hello world";
if(typeof(Object).IsAssignableFrom(str.GetType()))
{
    //instances of type String can be assigned to instances of type Object.
}

if(typeof(Object).IsAssignableFrom(typeof(string)))
{
    //instances of type String can be assigned to instances of type Object.
}

请注意,IsAssignableFrom() 的参数不是 String 的实例,而是表示 String 类型的 Type 对象。

is keyword is only applicable for instances while Type.IsAssignableFrom() is only applicable for types.

example of is

string str = "hello world";
if(str is String)
{
    //str instance is of type String
}

Note that str is an instance and not the type.

example of IsAssignableFrom()

string str = "hello world";
if(typeof(Object).IsAssignableFrom(str.GetType()))
{
    //instances of type String can be assigned to instances of type Object.
}

if(typeof(Object).IsAssignableFrom(typeof(string)))
{
    //instances of type String can be assigned to instances of type Object.
}

Note that, argument to IsAssignableFrom() is not the instance of String, it's the Type object representing String type.

逆蝶 2024-09-12 06:23:28

一个显着的区别还在于,“is”对于测试继承或接口实现具有直观意义,而 IsAssignableFrom 从表面上看毫无意义。当应用于测试继承或检测接口实现时,Type.IsAssignableFrom 方法的名称模糊且令人困惑。用于这些目的的以下包装器将产生更加直观、可读的应用程序代码:

    public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
    {
        // Always return false if either Type is null
        if (CurrentType == null || TypeToCompareWith == null)
            return false;

        // Return the result of the assignability test
        return TypeToCompareWith.IsAssignableFrom(CurrentType);
    }

然后,可以拥有更易于理解的客户端语法,例如:

    bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
    CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));

此方法而不是“is”关键字的优点是它可以在运行时使用测试未知的任意类型,而“is”关键字(和通用类型参数)需要特定类型的编译时知识。

A notable difference is also that 'is' makes intuitive sense for testing inheritance or interface implementation, whereas IsAssignableFrom makes anything but sense on the face of it. The name of the Type.IsAssignableFrom method is vague and confusing when applied to testing inheritance or detecting interface implementations. The following wrapper for these purposes would make for much more intuitive, readable application code:

    public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
    {
        // Always return false if either Type is null
        if (CurrentType == null || TypeToCompareWith == null)
            return false;

        // Return the result of the assignability test
        return TypeToCompareWith.IsAssignableFrom(CurrentType);
    }

Then, one can have more understandable client syntax like:

    bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
    CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));

The advantage of this method instead of the 'is' keyword is that it can be used at run-time to test unknown, arbitrary Types, whereas the 'is' keyword (and a generic Type parameter) requires compile-time knowledge of specific Types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文