如何在方法中传递我的对象列表? [英] How can I pass list of my object in method?

查看:45
本文介绍了如何在方法中传递我的对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜欢我问:例如,我有两个不同的列表:

List< myoldobject>旧的;

列表< mynewobject> mnew;



所以,我想在其中一个参数中做一个方法,我可以传递字符串和列表



我不想通过两个清单。



我该怎么做?



我的尝试:



Liked I asked: For example I have two diffrent list:
List<myoldobject> old;
List<mynewobject> mnew;

So, I'd like to do method witch in one of parametrs I can pass string and list

I don't want pass two list.

How can I do that?

What I have tried:

public void save(List<myoldobject> obj ,string s) // I don't know what I should write in "<>"
{}

推荐答案

有几种方法。

1)你可以创建重载方法:

There are a couple of ways.
1) You can create overloaded methods:
public void save(List<myoldobject> obj ,string s)
{
   ...
}



And

public void save(List<mynewobject> obj ,string s)
{
   ...
}



2)您可以定义一个接口IMyObject,您的类都可以实现它(它不需要任何方法)并将其用于通用实现:


2) You could define an interface IMyObject which both your classes implement (it needs no methods) and use that for a generic implementation:

public interface IMyObject { }
public class myoldclass : IMyObject { }
public class mynewclass :IMyObject { }

然后你可以传递给你方法:

You can then pass either to your method:

public void save<T>(List<T> list, string s) where T: IMyObject
    {
    }




List<myoldclass> a = new List<myoldclass>();
List<mynewclass> b = new List<mynewclass>();
save(a, "");
save(b, "");

但是......在你的方法中,你将无法使用任何不属于界面的类成员。

But ... inside your method, you won't be able to use any class members which are not part of the interface.


它取决于你想在方法中做什么,但你可以:

It depends on what you want to do in the method, but you can:
public void save<T>(List<T> list, string s)
{

}


public class Result <T>
{
  public T List { get; set; }
}

	

Result<Object> Info = new Result<Object>();
Info.List = anyList;
save(Info, "string");



 public void save(Result<Object> List, string info)
 {
    .............
 }


这篇关于如何在方法中传递我的对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆