[英]C# - How are we supposed to implement default(T) in Interfaces?
Put default(T)
in an interface. 将
default(T)
放在界面中。
Explicitly
implement the interface.
明确地
实现接口。 The result does not compile 结果无法编译
public interface IWhatever<T>
{
List<T> Foo(T BarObject = default(T));
}
public class ConcreteWhatever: IWhatever<ConcreteWhatever>
{
List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(T)) {}
}
I fully expect default(ConcreteWhatever)
. 我完全期望
default(ConcreteWhatever)
。 What I get is default(T)
which results in a compilation error. 我得到的是
default(T)
,这会导致编译错误。
I just go in and replace default(T)
with null
and things are fine. 我只是进入并用
null
替换default(T)
,事情很好。 But this is hideous. 但这很可怕。 Why is this happening?
为什么会这样?
You don't have a T
in this case, because ConcreteWherever
isn't a generic type. 在这种情况下,您没有
T
,因为ConcreteWherever
不是泛型类型。
If you want default(ConcreteWhatever)
then that's the code you should write. 如果你想要
default(ConcreteWhatever)
那么那就是你应该编写的代码。
Are you just complaining about the code auto-generated by Visual Studio? 您是否只是在抱怨Visual Studio自动生成的代码? If so, that's a reasonable complaint, but it would be worth being explicit about it... (Note that you're not using explicit interface implementation here - otherwise it would be declared as
IWhatever<ConcreteWhatever>.Foo
. You don't really have properly implicit implementation either, as otherwise it should be public...) 如果是这样,这是一个合理的抱怨,但值得明确它...(请注意,你没有在这里使用显式接口实现 - 否则它将被声明为
IWhatever<ConcreteWhatever>.Foo
。你没有真的有正确的隐式实现,否则它应该公开...)
EDIT: I've just tried the same thing myself, and seen the same result, except the method is made public. 编辑:我自己尝试了同样的事情,并看到了相同的结果,除了方法是公开的。 Looks like it's just a fault with Visual Studio - I suggest you create a Connect request for it.
看起来这只是Visual Studio的一个错误 - 我建议你为它创建一个Connect请求。 It's a relatively rare situation though, I suspect - creating a generic interface which specifies an optional parameter which uses the default value of a type parameter as the value...
这是一个相对罕见的情况,我怀疑 - 创建一个通用接口,它指定一个可选参数,它使用类型参数的默认值作为值...
Shouldn't this line: 不应该这一行:
List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(T)) {}
be: 是:
List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(ConcreteWhatever)) {}
public interface IWhatever<T>
{
List<T> Foo(T BarObject = default(T));
}
public class ConcreteWhatever : IWhatever<ConcreteWhatever>
{
public List<ConcreteWhatever> Foo(ConcreteWhatever BarObject = default(ConcreteWhatever))
{
return null; // replace with proper code
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.