我脑子里死了; 我根据特定的类(c1,c2,c3 ......)定义了几个List'.我有一个方法来处理这些列表上的信息.我想要做的是传递特定列表,但让方法接受通用列表,然后通过typeof确定要执行的具体工作.我知道它可能,但我似乎无法在方法方面获得正确的语法.所以,例如:
List<c1> c1var;
List<c2> c2var;
List<c3> c3var;
some_method(c1var);
some_method(c2var);
some_method(c3var);
class some_thing
some_method(List<> somevar)
if typeof(somevar).name = x then
esle if typeof(somevar).name = y then....
Run Code Online (Sandbox Code Playgroud)
如何设置方法的参数列表?
谢谢R.桑德斯
JSB*_*ոգչ 46
您还需要声明some_method为通用的.
void SomeMethod<T>(List<T> someList)
{
if (typeof(T) == typeof(c1))
{
// etc
}
}
Run Code Online (Sandbox Code Playgroud)
小心使用typeof(typ1)== typeof(typ2).这将测试以查看类型是否等同于忽略类型层次结构.
例如:
typeof(MemoryStream) == typeof(Stream); // evaluates to false
new MemoryStream() is Stream; //evalutes to true
Run Code Online (Sandbox Code Playgroud)
检查对象是否属于某种类型的更好方法是使用'is'关键字.一个例子如下:
public static void RunSnippet()
{
List<c1> m1 = new List<c1>();
List<c2> m2 = new List<c2>();
List<c3> m3 = new List<c3>();
MyMeth(m1);
MyMeth(m2);
MyMeth(m3);
}
public static void MyMeth<T>(List<T> a)
{
if (a is List<c1>)
{
WL("c1");
}
else if (a is List<c2>)
{
WL("c2");
}
else if (a is List<c3>)
{
WL("c3");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37236 次 |
| 最近记录: |