Can a static class be imported in C # like in VB.NET?

Is there a way to “import” a static class into C #, such as System.Math ?

I turned on the comparison.

Imports System.Math

Module Module1

    Sub Main()
        Dim x As Double = Cos(3.14) ''This works
    End Sub

End Module

Vs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Math; //Cannot import a class like a namespace

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = Math.Cos(3.14);
            double y = Cos(3.14); //Cos does not exist in current context
        }
    }
}
+3
source share
5 answers

UPDATE: Starting with C # 6, the answer is now YES .


No, in C # you can import namespaces, not classes.

However, you can give it a shorter alias:

using M = System.Math;

Now you can use an alias instead of a class name:

double y = M.Cos(3.14);

Be careful how you use it. In most cases, the code is more readable with a descriptive type name Math, rather than a cryptic one M.


, , :

using StringBuilder = System.Text.StringBuilder;

StringBuilder System.Text.

+9

# 6.0, Using Static. , , Using Static System.Math; System.Math Math.

SO:
Math #?


# 6 " " ?

:
GitHub - # 6
Intellitect - Static Statement # 6.0

+8

. #.

+5

, , - ? , .

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = Math.Cos(3.14);
            double y = 3.14;
            Console.WriteLine(y.Cos());
        }
    }

    public static class Extension
    {
        public static double Cos(this double d)
        {
            return Math.Cos(d);
        }
    }
}
+2

Starting with C # version 6, static classes can be imported using the following syntax.

using static System.Console;
0
source

Source: https://habr.com/ru/post/1768723/


All Articles