2016-11-21 107 views
0

在我的控制檯程序中,我想通過使用System.Net.Mail.MailMessage發送電子郵件給某人。然而,我不能初始化它:(MailMessage是否需要任何設置來初始化?

名稱空間:

using System.Net; 
using System.Net.Mail; 

代碼:

class emailHelper 
{ 
    string to = "[email protected]"; 
    string from = "[email protected]"; 
    MailMessage message = new MailMessage(from, to);// errors here 
} 

該錯誤消息爲約:

甲字段初始不能引用非屬性'programA.emailHelper.from'

一個字段初始不能引用非靜態字段,方法或 財產「programA.emailHelper.to」

我根本不知道我錯過了什麼MAILMESSAGE使用前設置。

有什麼想法?

回答

0

錯誤信息給你所有的信息。如果你想它的工作

一個字段初始不能引用非靜態字段,方法或 財產

所以,你應該讓你的字符串字段靜態的。我懷疑是你想要的。

class emailHelper 
{ 
    static string to = "[email protected]"; 
    static string from = "[email protected]"; 
    MailMessage message = new MailMessage(from, to);// errors here 
} 

就像我說過的,這不是你想從一個輔助方法,要有靜態地址和從地址。您的代碼應該是這樣的:

public class EmailHelper 
{ 
    public string To {get; set;} 
    public string From {get; set;} 
    public MailMessage message {get; set;} 

    public EmailHelper(string to, string from) 
    { 
     To = to; 
     From = from; 

     message = new MailMessage(from, to); 
    } 

} 

在這種情況下,你有哪些是走出來的幫手的地址,你可以創建多個MailMessage類。

0

作爲錯誤消息指出

甲字段初始不能引用非靜態字段,方法或 屬性

這意味着你不能使用的字段來初始化另一個字段。但是你可以利用這裏的構造函數,類實施將是這樣的:

class emailHelper 
{ 
    string to = "[email protected]"; 
    string from = "[email protected]"; 
    MailMessage message; // Declare here 
    public emailHelper() // Constructor 
    { 
     message = new MailMessage(from, to);//initialize here 
    } 
} 

或者使用只讀屬性的getter這樣的:

public MailMessage Message 
{ 
    get { return new MailMessage(from, to); } 
} 
0

甲字段初始不能引用非靜態字段,方法或 屬性「字段」的實例字段不能被用於初始化的方法以外的其他 實例字段。如果你想初始化的方法外 變量,考慮執行初始化 類的構造函數

檢查裏面的文檔:Compiler Error CS0236

// CS0236.cs 
public class MyClass 
{ 
    public int i = 5; 
    public int j = i; // CS0236 
    public int k;  // initialize in constructor 

    MyClass() 
    { 
     k = i; 
    } 

    public static void Main() 
    { 
    } 
}