3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
int result;
if (parameter is ICollection<Cat>)
result = (parameter as (ICollection<Cat>)).Count;
else if (parameter is Cat)
result = (parameter as Cat).Id;

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
這不是您想要使用泛型的情況,因?yàn)檫@不是泛型的目的。
你在這里有兩個(gè)選擇。
要么你做兩個(gè)這樣的方法:
public void TestMethod(Cat cat) {...}
public void TestMethod(ICollection<Cat> cats) {...}
或者,如果您確實(shí)需要這種通用方法,則使用對(duì)象作為參數(shù)。
public void TestMethod(object obj)
{
Cat cat = obj as cat;
if(cat != null)
{
return;
}
ICollection<Cat> cats = obj as ICollection<Cat>;
if(cats != null)
{
}
}
但即便如此,如果您使用反射,這只是一個(gè)好主意。

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
試試這個(gè)可能對(duì)你有幫助
class Cat
{
public int Id { get; set; }
}
class Program
{
static void Main(string[] args)
{
Cat cat1 = new Cat { Id = 1 };
Cat cat2 = new Cat { Id = 2 };
ICollection<Cat> cats = new List<Cat>();
cats.Add(cat1);
cats.Add(cat2);
TestMethod<ICollection<Cat>>(cats);
TestMethod<Cat>(cat1);
}
public static void TestMethod<T>(T parameter)
{
if (typeof(T) == typeof(ICollection<Cat>)) //if (parameter is ICollection<Cat>)
{
ICollection<Cat> cats = parameter as ICollection<Cat>;
//Count your cats in count variable
int count = cats.Count;
}
else
if (typeof(T) == typeof(Cat)) // if (parameter is Cat)
{
Cat cat = parameter as Cat;
//Get id of your cat in id variable
int id = cat.Id;
}
}
}
- 3 回答
- 0 關(guān)注
- 206 瀏覽
添加回答
舉報(bào)