2016-04-23 88 views
0

我正在努力學習tweetinvi證書外,所以我有以下UI如何使用VAR任何功能

enter image description here

這些2方法,initAuthenticationstartAuthentication

private void initAuthentication() 
    {    
      var appCredentials = new TwitterCredentials(consumerKey, consumerSecret); 
      var authenticationContext = AuthFlow.InitAuthentication(appCredentials); 
      Process.Start(authenticationContext.AuthorizationURL); 

      //i am commenting the following code 

      //var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(textBox1.Text, authenticationContext); 
      //Auth.SetCredentials(userCredentials); 

      //so the user have some time to copy the pinCode 
      //paste them into available textbox 
      // and continue executing startAuthentication() by clicking authenticate button. 
    } 

private void startAuthentication (string pinCode) 
{ 
    //if we split like this, the authenticationContext is error, because it doesn't exist in current context 

    var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(pinCode, authenticationContext); 
    Auth.SetCredentials(userCredentials); 
} 

如果我們加入兩個部分在一個功能,沒有時間讓用戶複製粘貼PIN碼到文本框中。

然而,如果我們分開兩部分,不同的功能,有一段時間,用戶複製粘貼PIN碼到文本框,但似乎authenticationContext了錯誤,因爲it doesn't exist in current context

有什麼辦法如何解決這個問題?

+1

你只能在局部範圍內使用var而不是globar – Mostafiz

+0

@MostafizurRahman同意,但如何繞過或使我的代碼像我期望的那樣工作? – Cignitor

+0

您想使對話框爲模態,然後在按下驗證按鈕之前它不會返回到應用程序。 – Hogan

回答

3

我不知道這個API應該如何工作,但方法中創建的變量的範圍只存在於該方法中。

你有兩個選擇:

  1. 做出力所能及的類型由AuthFlow.InitAuthentication(appCredentials);返回的類變量,設置它在你的第一個方法,然後你可以從第二個方法訪問它。

  2. 將任何返回類型AuthFlow.InitAuthentication(appCredentials);的參數添加到第二個方法中,然後在調用第二個方法時傳入上下文。

編輯

就想過這個多一點,背景通常是你需要繞過了不少這樣的選擇1可能會更好一些。

編輯2

我看着它,並InitAuthentication回報IAuthenticationContext。所以後來在一個方法

_authContext = AuthFlow.InitAuthentication(appCredentials); 

使你的方法一類變量外像這樣

IAuthenticationContext _authContext; 

然後在方法二

var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(pinCode, _authContext); 

而且回答關於var的問題... var基本上是簡短的創建變量,而不必每次輸入類型。然而,var的一個注意事項是它所使用的變量必須被賦值,否則var無法推斷出基礎類型,並且會得到一個編譯器錯誤。

例如

var myVariable1; 

var myVariable1 = null; 

將拋出一個編譯時錯誤,因爲編譯器無法推斷類型爲myVariable1應該是什麼樣的方式。

正確的語法是

var myVariable1 = 4; 

或者

var myVariable1 = "hello world"; 

或者

var myVariable1 = SomeMethodThatReturnsSomething(); 
0

創建類的字段,而不是局部變量

class ClassName 
{ 
    AuthenticationContext authenticationContext; 

    private void initAuth() 
    { 
     // set authenticationContext 
     authenticationContext = AuthFlow.InitAuthentication(appCredentials); 
    } 

    private void startAuth(string pin) 
    { 
     // use authenticationContext 
    } 
}