2013-08-02 37 views
0

如何設置對象的名稱空間?爲C中的對象創建名稱空間#

現在我必須按以下方式使用一個對象。 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 
+0

你有沒有試着用的命名空間類似NameSpace.ClassName TC的名稱前綴的類名=新NameSpace.ClassName –

+0

這是類''MyFirstTestCase? – Praveen

回答

0

您的課程通常已經在名稱空間中。如果沒有,你可以通過只包裹了整個事情的命名空間塊手動添加一個:

namespace Something.Here 
{ 

    public class MyClass 
    { 

    } 

} 

那麼你就可以這樣做:

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

在C#中你不能做到這一點 - 它不是VB。

1

不可能。如果你在同一個班上工作,你可以直接調用方法,就像你想要的那樣。但是在一個實例化的對象上,你必須使用你創建的變量。在VB中,它有一個WITH關鍵字用於範圍的一部分代碼,但C#沒有這個。問題更新後

WITH object 
    .methodA() 
    .methodB() 
END WITH 
-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信息。

+0

這並不像所假設的那樣工作。我仍然必須寫'testCase.DoThis();' – wewa

+0

不要以爲OP是在問這個問題,他是在尋求c#WITH的等價物。您的DoThis()和DoThat()不是MyFirstTestCase的方法,如果他們是在調用中需要實例或類的話。 – Adrian

+0

這不是使用聲明的工作原理。 using語句不會創建一個不同的作用域,它唯一的作用是在運行代碼塊後指定的對象上調用dispose方法。處置也與OP的問題無關。你指的是VB – Kenneth

0

需要通過實例訪問實例方法。所以你不能那樣做。

0

WITH塊不是C#的一部分,你可以通過鏈接方法來獲得類似的功能。基本上每個方法都會返回這個。所以,你可以寫類似的代碼:

tc.DoThis().DoThat(); 

這也可以寫成

tc 
.Dothis() 
.DoThat(); 
0

什麼是像這樣做的原因是什麼?你是否厭倦了不時在前綴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.... 
;