我有一些代码正在寻找具有特定属性的构造函数,如下所示:
...
ConstructorInfo ctor;
var ctors = valueType.GetTypeInfo().DeclaredConstructors;
foreach (var ictor in ctors) {
foreach (object attr in ictor.GetCustomAttributes(false)) {
if (attr is MyConstructor) {
ctor = ictor;
goto Found;
}
}
}
throw new Exception($"Unable to find appropriate Constructor.");
Found:
... // do something with ctor
(OMG转到!)
我的问题是-用Linq可以做得更好吗?如果是,怎么办?
答案 0 :(得分:3)
这是一个尝试
var ctors = valueType.GetTypeInfo().DeclaredConstructors;
ConstructorInfo ctor = ctors.FirstOrDefault(x=> x.GetCustomAttributes(false).Any(a=> a is MyConstructor));
if (ctor != null)
goto Found;