如何创建只接受数字和布尔值的动态类型变量?
How to create dynamic type variable which will accept only number and bool?
如何创建只接受 bool
和 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.
您可以定义一个仅接受 bool
或 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);
如何创建只接受 bool
和 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.
您可以定义一个仅接受 bool
或 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);