首页 > 解决方案 > 如何创建只接受数字和布尔值的动态类型变量?

问题描述

如何创建只接受booland的动态类型int

我知道这可以通过以下方式手动完成:

if ( smth is bool || smth is int){
    dynamic myValue = smth;
}

但是,我可以创建一个避免我手动检查的类型,所以我可以直接:

dynamic myValue = smth ;   //if it is not either `int` nor `bool` then throw error. otherwise, continue script.

标签: c#.net-4.5

解决方案


您可以定义一个只接受 abool或a 的自定义类型int

public readonly struct Custom
{
    public readonly bool _bool;
    public readonly int _int;

    public Custom(bool @bool)
    {
        _bool = @bool;
        _int = default;
    }

    public Custom(int @int)
    {
        _bool = default;
        _int = @int;
    }
}

那么这将起作用:

dynamic b = true;
Custom custom = new Custom(b);

...但这会在运行时引发异常:

dynamic s = "abc";
Custom custom = new Custom(s);

推荐阅读