问题描述
// OK
结构MYSTRUCT
{
静态无效美孚(){}
}
//错误
静态结构MYSTRUCT
{
}
由于无法创建一个静态类型的实例,静态结构的行为
将是完全一样的<$ C的行为$ C>静态类。因此,没有理由为创建它们。我认为这将是理论上可以有一个静态结构
但它会是混乱 - 你会如何静态类和
静态结构
如果两个行为是的究竟的一样吗?
需要注意的是静态
一个结构里面的方法是,你可以将它们用于相关的结构操作非常有用,例如 DateTime.TryParse 等
从技术上讲我不认为目前的C#编译器和放大器;运行时可能会产生像一个静态结构
,因为内部(在IL级)静态类
是一类就是标记为摘要
和密封
。而且我想你不能创建一个结构
这将是摘要
和密封
(在IL)。
// OK
struct MyStruct
{
static void Foo() { }
}
// Error
static struct MyStruct
{
}
解决方案 Since you cannot create an instance of a static type, the behavior of static struct
would be exactly the same as the behavior of static class
. So, there is no reason for creating them. I think it would be theoretically possible to have a static struct
but it would be confusing - how would you choose between static class
and static struct
if the behavior of the two was exactly the same?
Note that static
methods inside a struct are quite useful as you can use them for operations related to the struct, for example DateTime.TryParse
etc.
Technically speaking I don't think that the current C# compiler & runtime could produce something like a static struct
, because internally (at the IL level) static class
is a class that is marked as abstract
and sealed
. And I suppose that you cannot create a struct
that would be abstract
and sealed
(in the IL).
这篇关于你为什么不能声明在C#中的静态结构,但它们可以有静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!