2016-09-14 143 views
0

我想創建一個通用圖像上傳函數,因此我可以將它用於包含FileContent,FileName和FileType的不同屬性名稱的不同類。爲各種類型設置傳遞參數的值c#

這是我到目前爲止所嘗試的,但顯然這是行不通的,因爲它沒有設置傳遞參數的值。

public static void StoreFile(this HttpRequestBase @this, byte[] fileContent, string fileName, string fileType) 
    { 
     if ((@this.Files != null) && (@this.Files.Count == 1)) 
     { 
      var file = @this.Files[0]; 
      if ((file != null) && (file.ContentLength > 0)) 
      { 
       var content = new byte[file.ContentLength]; 
       file.InputStream.Read(content, 0, file.ContentLength); 
       fileContent = content; 
       fileName = file.FileName; 
       fileType = file.ContentType; 
      } 
     } 
    } 

是否有任何方式傳遞匿名類型或在這種情況下會有所幫助?

+0

你是說你想要的'StoreFile'方法實際修改給出這樣參數的值他們可以在其他地方使用? – ThePerplexedOne

+0

@ThePerplexedOne確實。 –

+2

有關**傳遞引用**和**傳遞值**的更多信息,請參見此線程:http://stackoverflow.com/questions/555471/modify-method-parameter-within-method-or-return-結果 – ThePerplexedOne

回答

1

我相信您的解決方案是改變你的函數聲明讀起來像這樣:

public static void StoreFile(this HttpRequestBase @this,ref byte[] fileContent, ref string fileName, ref string fileType)

參考ThePerplexedOne的評論(or this)對於到底爲什麼這個工程。

+1

在這種情況下使用'out'而不是'ref'可能更合適。請參閱https://msdn.microsoft.com/en-us/library/t3c3bfhx.aspx –

+0

我不知道這一點。同意。 – DrSatan1

+0

你今天是[幸運10000](https://xkcd.com/1053/)之一。 –

0

這裏有一個方法來實現這一目標用行動代表:

這是您的泛型StoreFile方法,它會採取3名不同的動作代表作爲參數。

public static void StoreFile<T>(this HttpRequestBase @this, T specificClassObject, Action<T, byte[]> setFileContent, Action<T, string> setFileName, Action<T, string> setFileType) where T : class 
{ 
    if ((@this.Files != null) && (@this.Files.Count == 1)) 
    { 
     var file = @this.Files[0]; 
     if ((file != null) && (file.ContentLength > 0)) 
     { 
      var content = new byte[file.ContentLength]; 
      file.InputStream.Read(content, 0, file.ContentLength); 
      setFileContent(specificClassObject, content); 
      setFileName(specificClassObject, file.FileName); 
      setFileType(specificClassObject, file.ContentType); 
     } 
    } 
} 

,這是你將如何調用StoreFile泛型方法對不同類型的對象:

// SpecificClass has properties byte[] PDFFileContent, string MyOrYourFileName and string ContentTypeWhatEver 
myHttpRequestBaseObject.StoreFile<SpecificClass>(specificClassObject, (x, y) => x.PDFFileContent = y, (x, y) => x.MyOrYourFileName = y, (x, y) => x.ContentTypeWhatEver = y);