![](/img/trans.png)
[英]c# FindSumSubset(decimal, ArrayList<decimal>)' has some invalid arguments
[英]C# Generics issue: some invalid arguments
public class ImgBuffer<T>
{
public T[] buf;
public int width;
public int height;
public ImgBuffer () {}
public ImgBuffer (int w, int h)
{
buf = new T[w*h];
width = w;
height = h;
}
public void Mirror()
{
ImageTools.Mirror (ref buf, width, height);
}
}
並且ImageTools類在第一個參數上為byte [],short []和Color32 []定義了Mirror。 尤其是:
public void Mirror(ref Color32[] buf, int width, int height) { ....
但是我得到這個錯誤:
錯誤CS1502:ImageTools.Mirror(ref Color32 [],int,int)'的最佳重載方法匹配具有一些無效的參數
我究竟做錯了什么?
您似乎希望C#泛型像模板一樣。 事實並非如此。 根據您的描述,似乎有一個ImageTools類,看起來像這樣
public class ImageTools
{
public static void Mirror(ref byte[] buf, int width, int height) { }
public static void Mirror(ref Color32[] buf, int width, int height) { }
public static void Mirror(ref short[] buf, int width, int height) { }
}
並且您有一個ImgBuffer類,看起來像這樣(略)
public class ImgBuffer<T>
{
public T[] buf;
public int width;
public int height;
public void Mirror()
{
ImageTools.Mirror(ref buf, width, height);
}
}
編譯器無法在ImgBuffer.Mirror
中驗證對ImageTools.Mirror
的調用是否合法。 編譯器對ref buf
所了解的所有信息都是T[]
類型的。 T
可以是任何東西。 它可以是字符串,整數,日期時間,Foo等。編譯器無法驗證參數是否正確,因此您的代碼是非法的。
這是合法的,但是我覺得您對3種所需類型的Mirror方法都有特定的實現,因此可能不可行。
public class ImageTools<T>
{
public static void Mirror(ref T[] buf, int width, int height) { }
}
您需要確定通用類型參數的范圍。 例如:
public class ImgBuffer<T> where T : Color32
{
public T[] buf;
public int width;
public int height;
public ImgBuffer () {}
public ImgBuffer (int w, int h)
{
buf = new T[w*h];
width = w;
height = h;
}
public void Mirror()
{
ImageTools.Mirror (ref buf, width, height);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.