代码中可否对类的某个方法临时改写
代码中能否对类的某个方法临时改写?
测试代码如下:主程序实例化 ClsAAA,然后执行 aaa.ff() 这个方法。
class Program
{
static void Main(string[] args)
{
ClsAAA aaa = new ClsAAA();
//aaa.ff = ShowNothing;
aaa.ff();
Console.ReadKey();
}
private void ShowNothing()
{}
}
class ClsAAA
{
public void ff()
{
Console.WriteLine("OK");
}
}
请问有没有办法让 ff变为ShowNothing(),这样执行 aaa.ff() 实际是执行ShowNothing,不显示任何东西出来。
------解决方案--------------------
------解决方案--------------------
nuget code --> Install-Package Moq
public class ClsAAA
{
public virtual void ff()
{
Console.WriteLine("OK");
}
}
var mock = new Mock<ClsAAA>();
mock.Setup(foo => foo.ff()).Callback(() => Console.WriteLine("ShowNothing()"));
mock.Object.ff();
------解决方案--------------------
比如32位.NET2.0的程序可以这样做
测试代码如下:主程序实例化 ClsAAA,然后执行 aaa.ff() 这个方法。
class Program
{
static void Main(string[] args)
{
ClsAAA aaa = new ClsAAA();
//aaa.ff = ShowNothing;
aaa.ff();
Console.ReadKey();
}
private void ShowNothing()
{}
}
class ClsAAA
{
public void ff()
{
Console.WriteLine("OK");
}
}
请问有没有办法让 ff变为ShowNothing(),这样执行 aaa.ff() 实际是执行ShowNothing,不显示任何东西出来。
------解决方案--------------------
class Program
{
static void Main(string[] args)
{
IClsAAA aaa = new ClsAAA();
//aaa.ff = ShowNothing;
aaa.ff();
Console.ReadKey();
}
}
interface IClsAAA
{
void ff();
}
class ClsAAA : IClsAAA
{
public void ff()
{
Console.WriteLine("OK");
}
}
//在测试代码中
public TestClsAAA : IClsAAA
{
public void ff()
{
ShowNothing();
}
}
private void ShowNothing()
{ }
public void TestClsAAA_ShowNothing()
{
IClsAAA aaa = new TestClsAAA();
aaa.ff();
}
------解决方案--------------------
nuget code --> Install-Package Moq
public class ClsAAA
{
public virtual void ff()
{
Console.WriteLine("OK");
}
}
var mock = new Mock<ClsAAA>();
mock.Setup(foo => foo.ff()).Callback(() => Console.WriteLine("ShowNothing()"));
mock.Object.ff();
------解决方案--------------------
比如32位.NET2.0的程序可以这样做
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Explicit)]