我想概括地提供动作/方法的封装。我认为这在C#中应该是可能的,但我无法生成它,所以它编译.
下面简要地说明了我想要的。这是可能的吗,也许通过泛化类来实现?
所要求的是:
void )boolean,并且值是false,则要‘做些什么’。公共类封装器{私有操作_action;私有Func _function;私有MethodType _type;//操作函数公共封装器( this._action ){this._action= action;this._type = MethodType.Action;}公共封装器( Function ){// this._function = func;this._type = MethodType.Function;} public void (){ try { this._action();}catch(异常ex) {//做一些抛出;}公共T执行(){ try { var = this._function();如果((R) == bool) { if(!r) //do }返回r;}catch(异常ex) {//做某事抛出;} }
发布于 2011-12-21 11:21:21
新方法:动作封装器现在将返回一个虚拟结果(始终为真)。
public class Encapsulator
{
public static Encapsulator<bool> CreateEncapsulator(Action action)
{
return new Encapsulator<bool>(() =>
{
action();
return true;
});
}
public static Encapsulator<T> CreateEncapsulator<T>(Func<T> func)
{
return new Encapsulator<T>(func);
}
}
public class Encapsulator<T>
{
private Func<T> _function;
internal Encapsulator(Func<T> func)
{
this._function = func;
}
public T Execute()
{
try
{
object res = this._function();
Nullable<bool> bres = res as Nullable<bool>;
if (bres.HasValue)
{
if (!bres.Value)
Console.WriteLine("NOT TRUE!");
//do something
}
return (T)res;
}
catch (Exception ex)
{
//do something
throw;
}
}
}调用代码:
var withDummyReturn = Encapsulator.CreateEncapsulator(() => Console.WriteLine("Great"));
withDummyReturn.Execute();
var withReturn = Encapsulator.CreateEncapsulator<bool>(() => true);
bool res = withReturn.Execute();发布于 2011-12-21 11:10:03
第二个构造函数不会编译,因为它们不是应用于更高级别的类型的泛型:
public Encapsulator<T>
{
public Encapsulator(Func<T> func)
{
this._function = func;
this._type = MethodType.Function;
}
}与其仅仅在方法的参数中引入新的东西,本质上,我们需要在定义中指定这些东西是“可用的”。因此,例如,如果您试图添加一个特定的泛型方法,您可以像您所做的那样应用它,但是需要这样做(您用Execute方法演示了一些事情):
public void MyGenericMethod<T>(Func<T> func)
{
} 注意到第一个T,我们就这样指定了T的存在。
这里的代码可能还有更多的问题,但我相信,乍一看,这是问题的症结所在。
至于返回变量类型,您可能希望返回一个普通的旧object。或者,使用dynamic类型,但是,我不会认为这是一种方法,也不会推荐它;不过,您不能将返回类型从实际类型切换到空类型。
https://stackoverflow.com/questions/8588812
复制相似问题