我写了这个博客:http://tri-katch.blogspot.com并实现了 pahakia-fault 库:https://github.com/pahakia/lib .
我想将 pahakia-fault 库转换为 C#。但是如何将以下内容翻译成 C# 呢?
public CodeBlockWorker<T> ignore(Class<? extends Throwable> clazz,
@SuppressWarnings("unchecked") Class<? extends Throwable>... classes) {
String[] codes = new String[classes.length];
for (int i = 0; i < codes.length; i++) {
Class<? extends Throwable> clz = classes[i];
codes[i] = clz.getName();
}
handlers.add(new KatchHandler<T>(clazz.getName(), codes));
return this;
}
我知道 C# 的 Type 相当于 Java 中的 Class,但 Type 没有参数化。
如果我想使用类型本身而不是它的实例,如何在 C# 中表示参数化类型?
谢谢。
最佳答案
我的java有点生疏,但我认为你想要完成的事情可以通过使用 GetType 来完成获取传递参数类型的方法:
public CodeBlockWorker<T> Ignore(
Exception clazz, params Exception[] classes)
{
handlers.add(
new KatchHandler<T>(
//You can use FullName if you want to include the namespace
clazz.GetType().Name,
classes.Select(t => t.GetType().Name)
/* might need to call .ToArray() if your Constructor expects an array */);
return this;
}
是的,简单介绍一下正在发生的事情。由于 .Net 中的任何“可抛出”异常(即可以在 try/catch 中使用的异常)都必须继承自 Exception
,因此您可以设置方法参数以使用 Exception
。 params
关键字只是对编译器的一个提示,允许将多个方法参数作为数组自动传递。
Object
具有方法 GetType
,它将返回该实例的类型。您可以通过 Name
仅获取类名,也可以通过 FullName
获取类名和命名空间。您还可以使用关键字typeof
来获取泛型参数的类型。
最后,.Select
方法具有一点 linq 的优点,该方法对可枚举(即数组)执行转换/投影,在本例中返回类中每个名称的可枚举
.
更新
如果您尝试处理类型而不是异常实例,您也可以尝试使用泛型类型参数和 typeof
关键字编写方法来获取类型参数的类型:
public CodeBlockWorker<T> Ignore<TClazz, TClasses>()
where TCLazz : Exception
where TClasses : Exception
{
var typename = typeof(TClazz).Name;
}
where
子句强制调用者传入异常类:
Ignore<NullReferenceException, ArgumentException>();
如果您希望允许调用者放置多个 TClass
,您必须为每个附加类型创建附加方法重载(这就是 Action 的实现方式:
Ignore<TClazz, T1, T2>(){}
Ignore<TClazz, T1, T2, T3>(){}
但是,您可以将这些覆盖中的每一个都输入到同一方法中:
private CodeBlockWorker<T> DoWork(Type TClazz, params Type[] TClasses){}
public CodeBlockWorker<T> Ignore<TClazz, T1, T2, T3>()
{
return DoWork(typeof(TClazz), typeof(T1), typeof(T2), typeof(T3));
}
或者你可以这样写,让调用者必须传入类型,但没有办法限制编译时传入的值;就像您无法创建一个具有将值限制为“5”和“42”的整数参数的方法一样;您只能在运行时执行此操作。
Ignore(Type clazz, params Type[] classes){
var typename = clazz.Name;
}
这将被称为:
Ignore(
typeof(NullReferenceException),
typeof(ArgumentException),
typeof(DivideByZeroException));
关于java - 参数化类型(如 Class<)的等效 C# 是什么?在 Java 中扩展 Throwable>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26440739/