希望有人能对此有所启发。我有一个带有可选参数的界面。我们使用Unity。如果我尝试更改方法实现中的可选参数,它会直接起作用,但 Unity 对象使用接口(interface)的默认值 - 而不是实现的方法的默认值。
设置:
public interface ITestOptional {
string HappyMethod(string input, bool amHappy = false);
}
public class TestingOptional : ITestOptional {
public string HappyMethod(string input, bool amHappy = true) {
if (amHappy) return input + " is Happy!";
return input + " is Not Happy!";
}
}
添加到Unity:
container.RegisterType<ITestOptional, TestingOptional>();
和测试:
//direct call
var testDirect = new TestingOptional();
string happyDirect = testDirect.HappyMethod("Cow", true); //expecting happy - get happy
string sadDirect = testDirect.HappyMethod("Cow", false); //expecting not happy - get not happy
string defaultDirect = testDirect.HappyMethod("Cow"); //expecting happy (default) get happy
//unity
var testUnity = ServiceLocator.Current.GetInstance<ITestOptional>();
string happyUnity = testUnity.HappyMethod("Cow", true); //expecting happy - get happy
string sadUnity = testUnity.HappyMethod("Cow", false); //expecting not happy - get not happy
string defaultUnity = testUnity.HappyMethod("Cow"); //expecting happy (default) but get NOT happy.
当实现使用 true 时,为什么 Unity 对象使用 false 作为可选参数,有什么想法吗?
最佳答案
ServiceLocator.Current.GetInstance<ITestOptional>();
返回编译类型ITestOptional
,所以请调用testUnity.HappyMethod("Cow");
将被编译器转换为使用接口(interface)中指定的默认值。
同样new TestingOptional();
返回编译时间TestingOptional
编译器将从类中选择默认值。
可能的解决方案(无需调整期望/不使用不同的默认值):您可以直接使用 Unity 解析该类型,而不是解析接口(interface)(有时对测试有用):
var directViaContainer = container.Resolve<TestingOptional>();
旁注:在实现接口(interface)的类中重新定义默认值并不是一种好的做法 - 您会经常遇到这种令人困惑的代码。
关于C# 接口(interface)、Unity 和可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950071/