import a static method

落花浮王杯 提交于 2020-01-11 08:05:52

问题


How can I import a static method from another c# source file and use it without "dots"?

like :

foo.cs

namespace foo
{
    public static class bar
    {
        public static void foobar()
        {
        }
    }
}

Program.cs

using foo.bar.foobar; <= can't!

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
             foobar();
        }
    }
}

I can't just foobar();, but if I write using foo; on the top and call foobar() as foo.bar.foobar() it works, despite being much verbose. Any workarounds to this?


回答1:


This is the accepted answer, but note that as the answer below states, this is now possible in C# 6

You can't

static methods needs to be in a class by design..

Why do static methods need to be wrapped into a class?




回答2:


With C# 6.0 you can.

C# 6.0 allows static import (See using Static Member)

You will be able to do:

using static foo.bar;

and then in your Main method you can do:

static void Main(string[] args)
{
    foobar();
}

You can do the same with System.Console like:

using System;
using static System.Console;
namespace SomeTestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Test Message");
            WriteLine("Test Message with Class name");
        }
   }
}

EDIT: Since the release of Visual Studio 2015 CTP, in January 2015, static import feature requires explicit mention of static keyword like:

using static System.Console;



回答3:


Declare an Action Delegate variable in a suitable scope as follows and use it later:

Action foobar = () => foo.bar.foobar();

or even easier

Action foobar = foo.bar.foobar;

I shall also pay attention to Extension Methods (C# Programming Guide). If you're having methods with parameters, often it's quite cosy to have:

public static class bar
{
    public static void foobar(this string value)
    {
    }
}

and utilize it:

 string s = "some value";
 s.foobar();

This is actually a much better approach.




回答4:


To add to the answers already here it's important to note that C# is a very typed language. Therefore, unless the method exists in the class you're in, you would never be able to do something like what you're looking for.

However, if you add the using:

using foo;

You can then access it with just the type and method like this:

bar.foo();


来源:https://stackoverflow.com/questions/14065342/import-a-static-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!