你为什么不能声明在C#中的静态结构,但它们可以有静态方法? [英] Why can't you declare a static struct in C#, but they can have static methods?

查看:121
本文介绍了你为什么不能声明在C#中的静态结构,但它们可以有静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  // 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#中的静态结构,但它们可以有静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆