2016-09-14 55 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);