2012-07-09 48 views
1

我遇到了一些語法問題。我對接口並不熟悉,請原諒我的無知。「使用未分配的本地變量」錯誤與接口

VS2010是給我一個錯誤的...... application.Name = System.AppDomain.CurrentDomain.FriendlyName;

public static void AddApplication(string applicationName = null, string processImageFileName = null) 
{ 
    INetFwAuthorizedApplications applications; 
    INetFwAuthorizedApplication application; 

    if(applicationName == null) 
    { 
     application.Name = System.AppDomain.CurrentDomain.FriendlyName;/*set the name of the application */ 
    } 
    else 
    { 
     application.Name = applicationName;/*set the name of the application */ 
    } 

    if (processImageFileName == null) 
    { 
     application.ProcessImageFileName = System.Reflection.Assembly.GetExecutingAssembly().Location; /* set this property to the location of the executable file of the application*/ 
    } 
    else 
    { 
     application.ProcessImageFileName = processImageFileName; /* set this property to the location of the executable file of the application*/ 
    } 

    application.Enabled = true; //enable it 

    /*now add this application to AuthorizedApplications collection */ 
    Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false); 
    INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType); 
    applications = (INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications; 
    applications.Add(application); 
} 

我可以作出這樣的錯誤設置applicationnull走開但導致運行時間空引用錯誤。

編輯:

這裏就是我適應從代碼。我希望它讓更多的上下文 http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx

+0

錯誤說明究竟是什麼錯誤。你聲明瞭一個變量並且從不初始化它。 – Wug 2012-07-09 20:05:47

+0

在你引用的代碼中,'applications'初始化爲'(INetFwAuthorizedApplications)mgr.LocalPolicy.CurrentProfile.AuthorizedApplications;'然後通過將每個條目分配給'application'來循環這個集合。你沒有這樣做。 – comecme 2012-07-09 20:16:06

回答

6

這裏使用它之前,你永遠不會初始化

application 

INetFwAuthorizedApplication application 

您需要:

application.Name = System.AppDomain.CurrentDomain.FriendlyName; 

爲變量的應用程序定義分配一個實現類的實例s接口INetFwAuthorizedApplication

某處必定有一個(或可能更多)班在你的項目是這個樣子:

public class SomeClass : INetFwAuthorizedApplication 
{ 
    // ... 
} 

public class AnotherClass : INetFwAuthorizedApplication 
{ 
    // ... 
} 

你需要確定你應該使用什麼類(SomeClass的,AnotherClass)然後分配一個合適的對象,例如像這樣:

INetFwAuthorizedApplication application = new SomeClass(); 
+0

我試着用「新」初始化它,但顯然我不能這樣做,因爲它是一個接口。我該如何解決這個問題? – Kashif 2012-07-09 20:06:10

+0

您需要將其設置爲實現該接口的對象的實例。 – 2012-07-09 20:06:44

+0

我真的很抱歉。你介意讓我昏昏沉沉嗎? – Kashif 2012-07-09 20:07:31

1

接口用於描述一個對象的功能,而不是具體是什麼。爲了投入「現實世界」,術語接口可能如下:

ISmallerThanABreadboxFitIntoBreadbox()方法。我不能要求你給我「小於麪包箱」......因爲這沒有任何意義。我只能要求你給我一些「比麪包箱小」的東西。你必須拿出你自己的對象,使其具有接口。一個蘋果比一個麪包盒小,所以如果你有一個只能容納比它小的產品的麪包箱,蘋果是一個很好的接口。

另一個示例是IGraspableHold()方法和FitsInPocket bool屬性。你可以要求給予一些可以或不可以放在口袋裏的東西,但是你不能要求「可以抓」。

希望可以幫助...

相關問題