Вопрос

У меня есть такой класс:

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;
    }  

Я хочу Изменить цену ничего не делать для определенного значения, но я также хочу вызвать конструктор, который установил цену 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;

Но даже если фальшивый хорошо инициализирован хорошим конструктором, я не могу назначить его @this.Я также пробую что-то вроде

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

Но на этот раз я не могу вызвать своего конструктора.Как мне поступить?

Это было полезно?

Решение

Вам не нужно издеваться над конструктором, конструктором без параметров Product class уже делает то, что вы хотите.

Добавьте немного отладочного вывода в 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

Кстати, здесь не нужно использовать заглушку,

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);

Другие советы

MProduct.Behavior = MoleBehaviors.Fallthrough;
.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top