[英]Generic parameter in c#
我有這個課程:
interface Info{}
class AInfo : Info { }
class BInfo : Info { }
class SendInfo {
static public f_WriteInfo(params Info[] _info) {
}
}
class Test {
static void Main() {
SendInfo.f_WriteInfo(
new[] {
new AInfo(){ ... },
new BInfo(){ ... },
} );
// This will generate an error.
// There will be need casting between new and [] like new Info[]
}
}
有沒有辦法在沒有鑄造的情況下做到這一點?
像:
class SendInfo {
static public f_WriteInfo(params T _info) where T : Info {
將您的方法簽名設置為:
static public f_WriteInfo(params Info[] _info) {}
並稱它為:
SendInfo.f_WriteInfo(new AInfo(){ ... }, new BInfo(){ ... });
這很好用
interface Info { }
class AInfo : Info { }
class BInfo : Info { }
class SendInfo
{
public static void f_WriteInfo(params Info[] _info)
{
}
}
class Test
{
static void Main()
{
SendInfo.f_WriteInfo(new AInfo(), new BInfo());
}
}
嘗試:
namespace ConsoleApplication1
{
interface Info{}
public class AInfo : Info
{
public AInfo(){}
}
public class BInfo : Info { }
class SendInfo {
public static void f_WriteInfo(params Info[] _info) {
}
}
class Program
{
static void Main(string[] args)
{
SendInfo.f_WriteInfo(
new Info[] {
new AInfo(),
new BInfo()
} );
}
}
}
來自MSDN
params 關鍵字允許您指定一個方法參數,該參數采用可變編號 arguments。您可以發送參數聲明中指定類型的逗號分隔列表 arguments,或指定類型的數組 arguments。 您也可以發送 no arguments。
所以arguments之前不需要寫new []
。
我想下面的鏈接也會有用
如何將單個對象傳遞給參數對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.