C# 接口(interface)、Unity 和可选参数

标签 c# interface optional-parameters

希望有人能对此有所启发。我有一个带有可选参数的界面。我们使用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/

相关文章:

c# - 有没有办法保存 DBSet 中的更改

c# - 如何使用 FileSystemGlobbing.Matcher

javascript - 当文本更改且文本框不失去焦点时调用方法

java - 弹珠程序未删除

c# - 如何将日期时间字段设置为null

c# - 如何以编程方式阅读 C# 中 WSDL 的文档部分

c# - 在 C# 中返回给定接口(interface)的泛型类型

c# - 将 null 传递给默认值为 null 的可选参数

wcf - 向WCF操作: choices?添加新参数

python - 默认数组参数意外不为空