gpt4 book ai didi

c# - 如何使用 Moles 作为构造函数?

转载 作者:太空狗 更新时间:2023-10-29 20:28:51 25 4
gpt4 key购买 nike

我有这样一个类:

public class Product : IProduct
{
static private string _defaultName = "default";
private string _name;
private float _price;
/// Constructor
public Product()
{
_price = 10.0F;
}
public void ModifyPrice(float modifier)
{
_price = _price * modifier;
}

我希望 ModifyPrice 对特定值不执行任何操作,但我还想调用将价格设置为 10 的构造函数。我试过如下操作:

var fake = new SProduct() { CallBase = true };
var mole = new MProduct(fake)
{
ModifyPriceSingle = (actual) =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
}
}
};
MProduct.Constructor = (@this) => (@this) = fake;

但即使 fake 已使用良好的构造函数进行了良好初始化,我也无法将其分配给 @this。我也尝试类似的东西

MProduct.Constructor = (@this) => { var mole = new MProduct(@this)... };

但是这次我不能调用我的构造函数。我该怎么办?

最佳答案

您不需要模拟构造函数,Product 类的无参数构造函数已经完成了您想要的操作。

Product 添加一些调试输出。

public class Product
{
private float _price;
public Product()
{
_price = 10.0F;
Debug.WriteLine("Initializing price: {0}", _price);
}
public void ModifyPrice(float modifier)
{
_price = _price*modifier;
Debug.WriteLine("New price: {0}", _price);
}
}

仅模拟 ModifyPrice 方法。

[TestMethod]
[HostType("Moles")]
public void Test1()
{
// Call a constructor that sets the price to 10.
var fake = new SProduct { CallBase = true };
var mole = new MProduct(fake)
{
ModifyPriceSingle = actual =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
}
else
{
Debug.WriteLine("Skipped setting price.");
}
}
};
fake.ModifyPrice(20f);
fake.ModifyPrice(21f);
}

查看调试输出以确认一切按预期工作:

    Initializing price: 10    Skipped setting price.    New price: 210

By the way, you don't need to use the stub here,

var fake = new SProduct { CallBase = true };

创建 Product 的实例就足够了。

var fake = new Product();

更新:可以像这样使用 AllInstances 类来模拟单个方法

MProduct.Behavior = MoleBehaviors.Fallthrough;
MProduct.AllInstances.ModifyPriceSingle = (p, actual) =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => p.ModifyPrice(actual));
}
else
{
Debug.WriteLine("Skipped setting price.");
}
};

// Call the constructor that sets the price to 10.
Product p1 = new Product();
// Skip setting the price.
p1.ModifyPrice(20f);
// Set the price.
p1.ModifyPrice(21f);

关于c# - 如何使用 Moles 作为构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com