【发布时间】:2013-11-14 04:21:37
【问题描述】:
是否有可能检查一个类型是否具有无参数构造函数,以便对其进行强制转换并调用需要具有: new() 约束的无参数构造函数的方法?
仅仅能够检查一个类型作为公共无参数回答here 是不够的,因为它不允许调用目标方法。
目标是有如下逻辑,其中IInteresting对象没有实现公共无参构造函数,需要在调用Save1之前进行转换:
public interface IInteresting { }
public void Save<T>(T o) {
var oc = o as (new()); /* Pseudo implementation */
if (oc != null) {
this.Save1(oc);
}
else {
var oi = o as IInteresting;
if (oi != null) {
this.Save2(oi);
}
}
}
private void Save1<T>(T o) where T : new() {
//Stuff
}
private void Save2<T>(IInteresting o) {
//Stuff to convert o to a DTO object with a public parameterless constructor, then call Save1(T o)
}
当然,如果我可以让Save1 和Save2 共享相同的签名来解决这个问题,但我找不到这样做的方法,因为以下内容无法编译(Routine、Save将调用第一个实现而不是第二个):
public void Routine<T>(T o) {
var oi = o as IInteresting;
if (oi != null) {
this.Save(oi);
}
}
private void Save<T>(T o) where T : new() {
//Stuff
}
private void Save<T>(IInteresting o) {
//Stuff to convert o to a DTO object with a public parameterless constructor, then call Save(T o)
}
【问题讨论】:
-
"还不够,因为它不允许调用目标方法。" - 实际上,它会的。
ConstructorInfo有一个Invokemethod。 -
只使用反射?但首先,重新考虑您的设计。
-
你的 Save1
方法里面有什么? -
Save 方法正在调用 ServiceStack.OrmLite 函数,该函数需要具有无参数构造函数的类型的对象。如果它还不是一个,我需要将对象转换为 DTO(尊重:new())。
-
@O.R.Mapper 我认为 ConstructorInfo 及其 Invoke 方法不允许我转换原始对象(仅创建一个新对象),对吗?
标签: c# interface casting signature type-constraints