我的代码尝试首先使用一个构造函数创建一个对象,然后,如果失败,则使用默认构造函数:
MyClass Construct(MyField f1, MyField f2)
{
try
{
return (MyClass)Activator.CreateInstance(typeof(MyClass), f1, f2);
}
catch
{
var o = (MyClass)Activator.CreateInstance(typeof(MyClass));
o.f1= f1;
o.f2=f2;
return o;
}
}
我想防止调试器在捕获异常时停止。我尝试了[DebuggerStepThrough]
,[DebuggerHidden]
和[DebuggerNonUserCode]
都没有运气。
我也尝试过跑步:"C:Program Files (x86)Microsoft Visual Studio2017CommunityCommon7IDEVsRegEdit.exe" set "C:Program Files (x86)Microsoft Visual Studio2017Community" HKLM DebuggerEngine AlwaysEnableExceptionCallbacksOutsideMyCode dword 1
按照这里的建议,但没有运气。
在VS2017中有什么方法可以做到这一点吗?或者,有没有办法使用将返回null
而不是引发异常的Activator.CreateInstance
?
(使用 Visual Studio 2017 15.8.0 预览版 4.0(
一个快速而令人讨厌的方法是寻找构造函数,GetConstructors
并查看GetParameters
计数,然后相应地进行分支。
var ctors = typeof(A).GetConstructors();
// assuming class A has only one constructor
var ctor = ctors[0];
foreach (var param in ctor.GetParameters())
{
Console.WriteLine(string.Format(
"Param {0} is named {1} and is of type {2}",
param.Position, param.Name, param.ParameterType));
}
再一次,可能有更好的方法来做到这一点。但是,至少您没有使用异常来控制应用程序的流。
如果您知道类的类型,还可以比较类型。或者,如果您使用的是基类或接口,则可以使用带有约束的泛型。这在很大程度上取决于我们看不到的东西和原因