c# - 如何创建只接受数字和布尔值的动态类型变量?
问题描述
如何创建只接受bool
and的动态类型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.
解决方案
您可以定义一个只接受 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);
推荐阅读
- reactjs - 反应原生:无法解析“@ant-design/icons-react-native/fonts/antoutline.ttf”
- c# - 如何在 C# 中显示一定时间的消息
- java - 为什么 Xamarin.Android 不是在自定义代理上构建,而是在 VSTS 默认 Visual Studio 2017 代理和 Visual Studio 中构建?
- git - 如何从一个远程获取并推送到另一个
- mule - Mule HTTP 连接器 - 访问资源需要会话
- python-2.7 - cx_Freeze: 'The system cannot find the file specified' during build [win10] [PyQt4] [python2.7] 错误
- c# - 刷新局部视图以重新加载 viewbag 下拉列表
- dji-sdk - 适用于智能控制器和 Mavic 2 Pro 的 DJI Mobile SDK - 无产品连接
- https - HTTPS 加密对我的域无效。我的订单证书未完成
- sql - 动态 SQL where 条件与来自另一个表的值