كيفية استخدام الشامات لمنشئ?
-
14-11-2019 - |
سؤال
لدي فئة مثل هذا:
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;
ولكن حتى لو مزيف تمت تهيئته جيدا باستخدام المنشئ الجيد ، ولا يمكنني تعيينه إلى @هذا.أنا أيضا أحاول شيئا مثل
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
بالمناسبة ، لا تحتاج إلى استخدام كعب هنا,
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);
نصائح أخرى
giveacodicetagpre.
لا تنتمي إلى StackOverflow