[英]How to pass the name of a class as paramenter to a method and instantiate that class inside the method?
我希望能够将类名称作为参数传递给方法,然后在该方法内部创建具有某些参数的该类的对象。
一个具体的(简化的)示例:
这是一种计算OperationResult的方法
private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides, IFailedOperationInfo failedOperationResult)
{
var exception = failedOperationResult.Exception.HasValue() ? failedOperationResult.Exception.Value() : null;
if (exception != null)
{
return new FailedResult<Unit>(
new InvalidBundleErrorKeyResolver(new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName, sides), exception)));
}
throw new InvalidOperationException("Failed operation result during bundle consistency check does not contain error or exception.");
}
根据获取错误的操作,我们使用不同的ErrorKeyResolvers。 我想将这些ErrorKeyResolver作为参数传递给方法,这样我就不需要为每种错误类型制作不同的GetFailedOperationResult方法。
受如何在C#中使用类名作为参数的启发,我尝试了以下操作:
private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides,IFailedOperationInfo failedOperationResult, IErrorResourceKeyResolver resourceKeyResolver)
{
var exception = failedOperationResult.Exception.HasValue() ? failedOperationResult.Exception.Value() : null;
if (exception != null)
{
return new FailedResult<Unit>(Activator.CreateInstance(typeof(resourceKeyResolver),new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName, sides), exception)));
}
throw new InvalidOperationException("Failed operation result during bundle consistency check does not contain error or exception.");
}
但是我不能做typeof(resourceKeyResolver)
因为我不能使用变量作为类型。
有没有很好的方法可以做到这一点? 这是一件好事吗? 我还读到应该避免动态变化,所以我想知道在这里保存一些代码重复是否值得。
编辑 :输入参数应为: private IOperationResult<Unit> GetFailedOperationResult(IEnumerable<StrictSide> sides,IFailedOperationInfo failedOperationResult, string resourceKeyResolver)
从类名作为字符串,我应该能够找到类型。
如果将类作为接口传递,则可以使用以下代码实例化解析器
var resolver = Activator.CreateInstance(resourceKeyResolver.GetType(),
new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName,
sides), exception));
否则,例如,如果您使用类名(assembly-qualified-name),则可以将其转换为first类型,然后再次调用上面的行
var resolverType = Type.GetType(resourceKeyResolverClassName);
var resolver = Activator.CreateInstance(resolverType ,
new FailedOperationInfo(new OperationInfo(failedOperationResult.OperationName,
sides), exception));
请参阅此处以获取GetType()
方法的文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.