在C#中为对象创建命名空间

时间:2013-08-02 07:31:42

标签: c# namespaces

如何设置对象的命名空间?

现在我必须以下列方式使用对象。 MyFirstTestCase tc = new MyFirstTestCase();

MyFirstTestCase tc = new MyFirstTestCase();
tc.dothis();
tc.dothat();
// ...

我想以这种方式使用对象。 MyFirstTestCase tc = new MyFirstTestCase();

MyFirstTestCase tc = new MyFirstTestCase();
using tc;
dothis();
dothat();
// ...

但这不起作用。我怎么能这样做?


澄清我的意思。

// MyFirstTestCase is the class
// tc is the object of MyFirstTestCase
// and instead of:
tc.dothis();
// ... I want to use:
dothis();
// dothis is a method of tc

8 个答案:

答案 0 :(得分:3)

你不能在C#中做到这一点 - 它不是VB。

答案 1 :(得分:1)

不可能。如果您正在使用同一个类,则可以直接调用方法,就像您希望的那样。但是在实例化对象上,您必须使用您创建的变量。在VB中,它有一个WITH关键字,用于范围代码的一部分,但C#没有这个。

WITH object
   .methodA()
   .methodB()
END WITH

答案 2 :(得分:0)

您的类通常已经在命名空间中。如果不是,您可以通过将整个事物包装在命名空间块中手动添加一个:

namespace Something.Here
{

    public class MyClass
    {

    }

}

所以你可以这样做:

Something.Here.MyClass my_class = new Something.Here.MyClass();

答案 3 :(得分:0)

这是VB.Net功能,C#不允许这样做。但请看一下 - http://www.codeproject.com/Tips/197548/C-equivalent-of-VB-s-With-keyword。这篇文章提出了一种简单的方法来获得你想要的东西。

答案 4 :(得分:0)

实例方法需要通过实例访问。所以你不能这样做。

答案 5 :(得分:0)

WITH块不是C#的一部分,你可以通过链接方法获得类似的功能。基本上每个方法都会返回此值。所以你可以编写如下代码:

tc.DoThis().DoThat();

也可以写

tc
.Dothis()
.DoThat();

答案 6 :(得分:0)

这样做是什么原因?你是否厌倦了不时为tc.加上前缀? :)如果你继续以更频繁的方式调用C#方法,那么这可能表明你的类没有很好的结构。

您可以将几个公共方法组合成一个然后在类中调用私有方法的方法,或者引入类似“链接”的方法,其中void方法通常使用this返回其类实例:

改变这个:

public class MyFirstTestCase {
    public void MyMethod1() {
       // Does some stuff
    }
    public void MyMethod2() {
       // Does some stuff
    }
}

分为:

public class MyFirstTestCase {
    public MyFirstTestCase MyMethod1() {
       // Does some stuff
        return this;
    }
    public MyFirstTestCase MyMethod2() {
       // Does some stuff
        return this;
    }
}

你现在可以做的是:

MyFirstTestCase tc = new MyFirstTestCase();
tc
    .MyMethod1()
    .MyMethod2()
    // etc.... 
;

答案 7 :(得分:-1)

问题更新后编辑:

那么,您实际上希望能够从MyFirstTestCase课程中调用方法,但是没有使用您的课程实例对其进行限定?

嗯,你做不到。

或者:

var testCase = new MyTestCase(); // Create an instance of the MyTestCase class
testCase.DoThis(); // DoThis is a method defined in the MyTestCase class

或:

MyTestCase.DoThis(); // DoThis is a static method in the MyTestCase class

有关static keywordhow to define static members in a class

的信息