2012-05-28 62 views
1

我想在Windows服務中的主類中定義一個屬性。該屬性將用於在需要時檢索過程的名稱。通過屬性檢索過程

對於如:

public string PName 
{ 
return SomeProcess.Name; 
} 

public string PID 
{ 
return SomeProcess.ProcessId; 
} 

public Process SomeProcess 
{ 
private Process[] myProcess = Process.GetProcessesByName("notepad"); //Process is underlined here with red wavy line saying "A get or set accessor method is expected" 
get 
{return myProcess[0];} 
} 

的問題是寫在註釋中SomeProcess屬性裏面。我在這裏做錯了什麼?

回答

4

讓這樣的:

private Process[] myProcess = Process.GetProcessesByName("notepad"); 
public Process SomeProcess 
{ 
    get 
    { 
     return myProcess[0]; 
    } 
} 

public Process SomeProcess 
{ 
    get 
    { 
     Process[] myProcess = Process.GetProcessesByName("notepad"); 
     return myProcess[0]; 
    } 
} 

編輯

請注意,您需要決定何時你想獲得的過程。如果你這樣做,就像我在第一個示例中展示的那樣,當類實例化時,過程將被檢索。第二種方式更強大,因爲當您詢問物業的價值時,它將檢索流程。

我說這兩個答案,因爲你問什麼錯誤的意思是更多關於私人和本地變量。

1

試試這個:

public Process SomeProcess 
{ 
    get 
    { 
     Process[] myProcess = Process.GetProcessesByName("notepad"); 
     return myProcess[0]; 
    } 
} 

或者這樣:

private Process[] myProcess = Process.GetProcessesByName("notepad"); 

public Process SomeProcess 
{ 
    get 
    { 
     return myProcess[0]; 
    } 
} 

要麼宣佈myProcessSomeProcess getter中的局部變量,或者如果你想聲明它的類中的私有字段在課堂其他地方使用它。你可以在字段/方法/類中使用訪問器(private/public/etc),而不是局部變量。

0

如果要聲明屬性中的get方法中的私有變量聲明。 根據您的代碼,您需要檢查GetProcessesByName是否返回進程或訪問myProcess[0]之前。您可以通過使用FirstOrDefault來避免所有這些驗證。如果沒有結果,它將返回null。

public Process SomeProcess 
{ 
    get 
    { 
     return Process.GetProcessesByName("notepad").FirstOrDefault(); 
    } 
} 

其他屬性也有問題。您可以在不檢查爲空的情況下訪問SomeProcess的屬性。

public string PName 
{ 
    return SomeProcess==null? string.Empty:SomeProcess.Name; 
} 

public string PID 
{ 
    return SomeProcess==null? string.Empty:SomeProcess.ProcessId; 
} 
0

我覺得你是在非常初級的水平,應該指的是語言代碼的語法,找到C#

public class ProcessInfo 
{ 
    private Process[] myProcess = Process.GetProcessesByName("notepad"); //Process is underlined here with red wavy line saying "A get or set accessor method is expected" 
    public Process SomeProcess 
    { 
     get 
     { 
      return myProcess[0]; 
     } 
    } 

    public string PName 
    { 
     get 
     { 
      return SomeProcess.ProcessName; 
     } 
    } 

    public int PID 
    { 
     get 
     { 
      return SomeProcess.Id; 
     } 

    } 
} 
下面的代碼