【发布时间】:2012-09-20 05:06:26
【问题描述】:
我正在尝试重构一段代码,但我想不出任何选项。
这是我的原始代码:
if (WebConfigSettings.ComPartition == null && HttpContext.Current != null)
Nses = new NSession();
else
Nses = (INSession)Marshal.BindToMoniker(string.Format("partition:{0}/new:NuntioServer.NSession", WebConfigSettings.ComPartition));
与
if (WebConfigSettings.ComPartition == null && HttpContext.Current != null)
apses.Wses = new WSession();
else
apses.Wses = (IWSession)Marshal.BindToMoniker(string.Format("partition:{0}/new:NuntioServer.WSession", WebConfigSettings.ComPartition));
这就是我尝试重构它的方式:
(是的,在 C# 中你可以instantiateaninterface。)
public static TInterface Get<TSubInterface, TInterface>() where TSubInterface: TInterface
{
<snip></snip>
if (!useComPartitions)
return Activator.CreateInstance<TSubInterface>(); // --> this is not cooperating
return (TInterface)Marshal.BindToMoniker(.....);
}
这是我已经尝试过的:
我尝试指定 new() 约束,然后执行“new TSubInterface()”: 这会导致构建错误:“..必须是具有公共无参数构造函数的非抽象类型,才能将其用作泛型类型或方法中的参数'TSubInterface'..”
当我使用 Activator.CreateInstance 时,出现运行时异常:“无法创建接口的实例”
当我使用 Activator.CreateComInstanceFrom("someAssemblyName", "typeName") 时,出现编译错误:“无法将表达式类型 'System.Runtime.Remoting.ObjectHandle' 转换为返回类型 TInterface”
[edit] 我可以通过添加 'where TSubInterface : class 来编译这个,但我不确定这是否有意义,因为 TSubInterface 是一个接口。
使用 CreateComInstanceFrom 也不起作用,因为它试图找到在该 dll 不存在且不应该存在的目录中指定的程序集。
我能以某种方式编译并运行它吗?
【问题讨论】:
-
你用哪个代码这个方法?
-
nses = COMUtils.Get
() NSession 和 INSession 都是接口。 -
您希望它工作只是因为您可以或打算在生产代码中使用它?如果是另一个,那么你最好使用一些控制容器的反转来实现类似的事情。
-
如果任何魔法让您通过 C#(即在您的链接中)实例化接口在通过反射工作时不适用,我不会感到惊讶。我怀疑编译器会将链接的代码翻译成标准的类实例化 IL,但是反射没有这个选项。
-
我被
Both NSession and INSession are interface弄糊涂了,你有一个约束NSession : INSession。这些真的是两个接口,一个继承另一个吗?如果是这样,为什么模板TClass中的接口的名称。