簡體   English   中英

為什么在 C# 中將靜態類型傳入和傳出接口方法是有效的?

[英]Why is it valid to pass static types in and out of interface methods in C#?

我注意到以下代碼似乎編譯得很好,而我預計會出現多個錯誤:

public interface ITest
{
    Math Foo(MathF x, ref Console y);
}

Math、MathF 和 Console 都是靜態類 - 有什么理由證明這是有效的,還是只是規范/編譯器的奇怪之處? 在嘗試實現接口時,您會收到一個錯誤(我想這意味着您可以制作一個無法實現的接口,這有點酷)

更重要的是,我可以做得更糟:

using System;

namespace StaticParams
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ITest.Bar(null);
        }

        public interface ITest
        {
            Math Foo(MathF x, ref Console y);

            static void Bar(Math x)
            {
                Baz(x);
            }

            static void Baz(Math x)
            {
                Console.WriteLine("Hello World" + x + "!"); // x is null so we can't do much with it
            }
        }
    }
}

輸出:

Hello World!

在 VS 2022 中測試,同時使用 C# 8.0 + .NET Core 3.1 和 C# 10.0 + .NET 6.0.4。

有什么理由證明這是有效的,還是只是規范/編譯器的奇怪之處?

像這樣的問題可能很難回答。 嚴格的字面答案是因為這就是 C# 語法的定義方式。

引用https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces

interface_declaration
    : attributes? interface_modifier* 'partial'? 'interface'
      identifier variant_type_parameter_list? interface_base?
      type_parameter_constraints_clause* interface_body ';'?
    ;
interface_body
    : '{' interface_member_declaration* '}'
    ;
interface_member_declaration
    : interface_method_declaration
    | interface_property_declaration
    | interface_event_declaration
    | interface_indexer_declaration
    ;
interface_method_declaration
    : attributes? 'new'? return_type identifier type_parameter_list?
      '(' formal_parameter_list? ')' type_parameter_constraints_clause* ';'
    ;

接口方法聲明的屬性、return_type、標識符和formal_parameter_list 與類中方法聲明的含義相同( 第14.6 節)。

從那里你將不得不用這個來敲自己: https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/classes#146-methods


但這當然不是一個真正有啟發性的答案。 我認為您真正想知道的是“允許這種精神錯亂的智慧是什么?”。 這當然是一個基於意見的問題。 所以我會用我的這些觀點來回答這個問題:

  • 在這個級別上阻止它可能只會使語言或其實現更加復雜
  • 它已經在另一個層面上被阻止了——正如你所指出的那樣實現該接口是不可能的,所以已經沒有人能夠編寫這樣有用的代碼
  • 當外面已經有這么多其他瘋狂時,為什么不允許它呢?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM