要求在FAIL上抛出特定exception类型的通用方法
是的,我知道我完全会看到这个人的白痴,但我的大脑今天早上并没有开始。
我希望有一种方法,我可以说“如果它变坏了,请回到这种类型的exception”,对吧?
例如,类似的东西( 这不起作用 ):
static ExType TestException(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; }
现在让我感到困惑的是,我们知道generics类型由于where子句而属于Exception类型。 但是,代码失败是因为我们无法隐式地将Exception 强制转换为ExType 。 我们也无法明确转换它,例如:
static ExType TestException(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; }
因为那也失败了。那么这种事情可能吗? 我有一种强烈的感觉,它会变得非常简单,但是我和老头脑一起度过艰难的一天,所以让我有些松懈:P
更新
感谢回复的人,看起来我不是一个完全白痴! ;)
好的,所以Vegard和Sam让我能够实例化正确的类型,但显然卡住了,因为消息参数在实例化后是只读的。
Matt用他的回答击中了正确的指甲,我测试了这一切,一切正常。 这是示例代码:
static ExType TestException(string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; }
甜! ?
多谢你们!
你几乎可以这样做:
static void TestException(string message) where E : Exception, new() { var e = new E(); e.Message = message; throw e; }
但是,这不会编译,因为Exception.Message是只读的。 它只能通过将它传递给构造函数来赋值,并且没有办法用非默认构造函数来约束generics类型。
我认为你必须使用reflection(Activator.CreateInstance)来使用message参数“new up”自定义exception类型,如下所示:
static void TestException(string message) where E : Exception { throw Activator.CreateInstance(typeof(E), message) as E; }
编辑哎呀刚刚意识到你想要返回exception,而不是抛出exception。 同样的原则适用,所以我将把我的答案保留为throw语句。
解决方案的唯一问题是可以创建Exception的子类,它不实现具有单个字符串参数的构造函数,因此可能抛出MethodMissingException。
static void TestException(string message) where E : Exception, new() { try { return Activator.CreateInstance(typeof(E), message) as E; } catch(MissingMethodException ex) { return new E(); } }
我一直在实例化内联我要抛出的exception类型,如下所示:
if (ItemNameIsValid(ItemName, out errorMessage)) throw new KeyNotFoundException("Invalid name '" + ItemName + "': " + errorMessage); if (null == MyArgument) throw new ArgumentNullException("MyArgument is null");
你有没有尝试过:
static T TestException(string message) {}
因为我觉得不需要输入generics约束,因为所有可抛出的exception都必须从System.Exceptioninheritance。
请记住,generics确实接受inheritance的类型。
我认为因为所有exception都应该有一个无参数构造函数,并且具有Message
属性,所以以下内容应该有效:
static ExType TestException(string message) where ExType:Exception { ExType ex = new ExType(); ex.Message = message; return ex; }
编辑:好的,消息是只读的,所以你必须希望该类实现exception(字符串)构造函数。
上述就是C#学习教程:要求在FAIL上抛出特定exception类型的通用方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
static ExType TestException(string message) where ExType:Exception { return new ExType(message); }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1007225.html