我经常发现需要按照这些思路做一些事情:
public class OperationResult
{
bool succes;
SomeOtherObject someobject;
}
public interface ICanDoSomethingWeird
{
OperationResult DoMyThing();
}
其中 OperationResult 实际上是一个属于 ICanDoSomethingWeird 接口(interface)的类。我觉得很烦我不能把它放在接口(interface)的命名空间中。 我想知道其他人如何处理这个问题。你只是把它放在全局命名空间中吗?还是仅从接口(interface)所在的命名空间向上一个命名空间?
我目前的方法是将 OperationResult 类重命名为 ICanDoSomethingWeird_OperationResult,但我对它的漂亮程度印象不深:)
有人有更好的解决方案吗?
最佳答案
如果 OperationResult
是 ICanDoSomethingWeird
和 ICanDoSomethingWeird
的客户端单独使用的类型,那么它属于与 相同的“上下文” >ICanDoSomethingWeird
。也就是说,它属于与ICanDoSomethingWeird
相同的命名空间:
namespace MyNamespace
{
public class OperationResult {}
public interface ICanDoSomethingWeird
{
OperationResult DoMyThing();
}
}
想想客户端代码。你喜欢这个吗:
using MyNamespace;
ICanDoSomethingWeird myWeirdThing = ...;
ICanDoSomethingWeird.OperationResult result = myWeirdThing.DoMyThing();
或者这个:
using MyNamespace;
ICanDoSomethingWeird myWeirdThing = ...;
OperationResult result = myWeirdThing.DoMyThing();
后者对我来说更有意义,并且是涉及接口(interface)的唯一选择。您不能在接口(interface)中声明内部类型。并注意 general advice关于嵌套类型:
DO NOT use nested types if the type is likely to be referenced outside of the containing type.
关于c# - 如何处理不允许在c#中的接口(interface)中定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/469028/