2012-01-19 29 views
1
public static void CopyProperties<T1, T2>(T1 objA, T2 objB) where T1 : new() 
{ 
} 

此方法的上述簽名編譯,但是我也想添加相同的「新」的條件爲T2不能找到正確的語法?

簽名香港專業教育學院嘗試,但不工作:

public static void CopyProperties<T1, T2>(T1 objA, T2 objB) where T1, T2 : new() 
    public static void CopyProperties<T1, T2>(T1 objA, T2 objB) where T1 : new(), where T2 : new() 

回答

5
public static void CopyProperties<T1, T2>(T1 objA, T2 objB) 
    where T1 : new() 
    where T2 : new() 
{ 
} 
+0

對於您添加的「新行」,爲+1。 – gdoron

1

只需添加最後的約束:

public static void CopyProperties<T1, T2>(T1 objA, T2 objB) where T1 : new() where T2 : new() 
{ 
} 
1

試試這個:

public static void CopyProperties<T1, T2>(T1 objA, T2 objB) 
where T1 : new() 
where T2 : new() 
0

此代碼提取會給你你在找什麼,它使用其中的關鍵詞爲您要添加的約束每種類型是很重要的,新的關鍵字必須是最後一個約束在每種類型。下面是一個示例

static void CopyProperties<T1, T2>(T1 objA, T2 objB) 
      where T1 : class, new() 
      where T2 : class, new()