简体   繁体   English

列出泛型和强制转换

[英]List Generics and Casting

I have two classes: Media and Container. 我有两节课:媒体和容器。

I have two lists List<Media> and List<Container> 我有两个列表List<Media>List<Container>

I'm passing these lists to another function (one at a time); 我将这些列表传递给另一个函数(一次传递一个)。

it can be one or another; 它可以是一个或另一个;

what's the proper way to check for the "template" type of the list so i can call an asssociated method depending on the list type? 什么是检查列表的“模板”类型的正确方法,以便我可以根据列表类型调用关联的方法?

or should i just try casting to the List<> and put Try/Catch blocks around it ? 还是我应该尝试转换为List <>并在其周围放置Try / Catch块?

    Object tagObj = mediaFlow1.BackButton.Tag;

    if (tagObj == Media)
       //do this
    else if (tagObj == Container)
        //do this
    else
        throw new Exception("Not a recognized type");

The proper thing to do is to have two overloads for this function, accepting each type: 正确的做法是此函数有两个重载,接受每种类型:

public void MyMethod(List<Media> source)
{
  //do stuff with a Media List
}

public void MyMethod(List<Container> source)
{
  //do stuff with a Container List
}

You can use the GetGenericArguments method of type Type, something like this: 您可以使用Type类型的GetGenericArguments方法,如下所示:

object[] templates = myObject.GetType().GetGenericArguments(); object []模板= myObject.GetType()。GetGenericArguments();

What David said. 大卫说了什么。

But if this must go through the same function, the typeof operator should help. 但是,如果必须通过相同的函数,则typeof运算符应该有所帮助。 Also, this sounds more like you have an architectural flaw. 同样,这听起来更像是您在体系结构上存在缺陷。 How is the Media class related to the Container class? Media类与Container类有什么关系? Is there some common interface used by both that they should implement? 两者都应该使用一些通用的接口吗?

Well, it depends on what your "//do this" method is... If it's a method that operates on a Media, or a Container object, and does different things based on which it is, then you should put that method in those classes... 好吧,这取决于您的“ //执行此”方法是什么...如果它是在Media或Container对象上运行的方法,并且根据其执行不同的操作,则应将该方法放入这些课...

Declare an interface named ICanDoThis 声明一个名为ICanDoThis的接口

public interface ICanDoThis { void DoThis(); }

make sure that both Media and Container implement that interface 确保Media和Container都实现了该接口

public class Media: ICanDoThis { // }
public class Container: ICanDoThis { // }

and then, in your client code "other function" you can 然后,在客户代码“其他功能”中,您可以

 public void OtherFunction(List<ICanDoThis> list)
 {
    foreach(ICanDoThis obj in list)
        obj.DoThis();
 }

And that's it... This code will call the appropriate implementation in either the Media Class or the Container class depending on what the concrete Type of the actual object is, without your having to write code to discriminate between them ... 就是这样...代码将根据实际对象的具体类型在Media类或Container类中调用适当的实现,而无需编写代码来区分它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM