是否可以为'Is 'c#中的操作符
本文关键字:操作符 Is 是否 | 更新日期: 2023-09-27 18:06:10
是否可以实现像
这样的方法调用?if (myString is Email)
其中Email
是类名,实际验证在"is"下执行,而不仅仅是类型检查。
不是为现实世界的项目,只是好奇。
不可以,因为is
操作符不能重载。阅读此处
为什么不创建一个自定义扩展方法并检入该方法呢
您可能会发现通过运算符:
部分解决方案是有用的 public class Email {
...
public static implicit operator Email(String value) {
if (...) // validate value here
return null; // <- not an actual Email
// Email
return new Email(value);
}
}
....
Email email = "SomeAddress@SomeServer.com";
if (email != null) {
...
}