您的位置:首页 > 其它

抽象类、接口、事件、Action、Func

2015-05-18 20:44 295 查看
抽象类负责对类的抽象,经常使用在Template等模式中

接口负责对类的行为的抽象

事件负责对两个对象的通信,而不需要建立两个对象直接联系,避免了对象的间的耦合

Action与Func在基于策略模式实现弱依赖关系,即Test(IStrategy strategy);实现对抽象方法取代真实方法的调用。

抽象类实现

public abstract class Test
{
public virtual int Add(int x,int y)
{
return x + y;
}

public abstract int Muliti(int x, int y);
}

接口实现

public interface IOperation
{
void Logger(string message);
}

public abstract class Test:IOperation
{
public virtual int Add(int x,int y)
{
return x + y;
}

public abstract int Muliti(int x, int y);

public void Logger(string message)
{
throw new NotImplementedException();
}
}

事件实现

public interface IOperation
{
void Logger(string message);
}

public abstract class Test:IOperation
{
public event Action OnRefresh;

public virtual int Add(int x,int y)
{
if (OnRefresh != null)
{
Action action = OnRefresh;
action();
}
return x + y;
}

public abstract int Muliti(int x, int y);

public void Logger(string message)
{
throw new NotImplementedException();
}
}

Action与Func实现对常见异常代码的封装和调用
class _09exception
{
public static void Main1()
{
BussinessHelper.Action(() =>
{
throw new MyException("aa", "bb");
});
}
}

class BussinessHelper
{
public static void Action(Action action)
{
try
{
if (action != null)
action();
}
catch (MyException ex)
{

}
}
}

class MyException : Exception
{
public MyException(string message)
: base(message)
{

}

public MyException(string message, string title)
:base(message)
{
Console.WriteLine(message);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: