如何将常量与C#中的接口相关联? [英] How to associate constants with an interface in C#?
问题描述
有些语言允许您将常数与界面相关联:
Some languages let you associate a constant with an interface:
- A Java example
- A PhP example
W3C抽象界面也是这样做的,例如:
The W3C abstract interfaces do the same, for example:
// Introduced in DOM Level 2:
interface CSSValue {
// UnitTypes
const unsigned short CSS_INHERIT = 0;
const unsigned short CSS_PRIMITIVE_VALUE = 1;
const unsigned short CSS_VALUE_LIST = 2;
const unsigned short CSS_CUSTOM = 3;
attribute DOMString cssText;
attribute unsigned short cssValueType;
};
我想定义此接口,以便可以从C#调用。
I want to define this interface such that it can be called from C#.
显然,C#无法定义与接口关联的常量。
Apparently C# cannot define a constant associated with an interface.
- 虽然C#不能,但是还有另一种.NET语言可以定义与接口相关的常量?
推荐答案
p>
To answer your third question:
虽然C#不能,但是还有另一种.NET语言可以定义与接口相关的常量吗?
Although C# cannot, is there another .NET language which can define constants associated with an interface?
C ++ / CLI允许您在接口中定义 literal
值,这等价于 static const
C++/CLI allows you to define literal
values in an interface, which are equivalent to static const
values in C#.
public interface class ICSSValue
{
public:
literal short CSS_INHERIT = 0;
literal short CSS_PRIMITIVE_VALUE = 1;
literal short CSS_VALUE_LIST = 2;
literal short CSS_CSS_CUSTOM = 3;
property DOMString^ cssText;
property ushort cssValueType;
}
然后,您可以通过C#访问这些值:
You could then access the values via C#:
public static void Main()
{
short primitiveValue = ICSSValue.CSS_PRIMITIVE_VALUE;
Debug.Assert(primitiveValue == 1);
}
See this page on MSDN for more details.
免责声明:
设计决定禁止接口中的常量值是一个很好的选择。暴露实现细节的接口很可能是泄漏抽象。在这个例子中CSS值类型可能更好一个枚举。
Disclaimer: The design decision to disallow constant values in interfaces was a good one. An interface which exposes implementation details is most likely a leaky abstraction. In this example CSS Value Type is probably better off being an enumeration.
这篇关于如何将常量与C#中的接口相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!