繁体   English   中英

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

[英]create namespace for an object in C#

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

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

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

我想以这种方式使用对象。 MyFirstTestCase tc =新的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

您无法在C#中执行此操作-它不是VB。

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

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

您的课程通常已经在名称空间中。 如果没有,您可以通过将整个内容包装在名称空间块中来手动添加:

namespace Something.Here
{

    public class MyClass
    {

    }

}

因此,您可以执行以下操作:

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

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

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

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

tc.DoThis().DoThat();

也可以写成

tc
.Dothis()
.DoThat();

这样做的原因是什么? 您是否厌倦了对tc.的前缀tc. 时? :)如果您继续在类上调用C#方法的频率更高,则可能表明您的类结构不够好。

您可以将几种公共方法组合成一个,然后在类中调用私有方法,或引入“链接”之类的方法,在这些方法中,通常空方法使用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.... 
;

问题更新后进行编辑:

因此,您实际上希望能够从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关键字以及如何在类中定义静态成员的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM