将类解析为可以继承的接口 [英] Parse classes to interface that can inherit

查看:105
本文介绍了将类解析为可以继承的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我今天在这里玩转接口,以尝试更好地使用它们(cos我从不使用任何东西,但抽象类cos,我从不觉得接口有很多用),但是我编写了以下代码:

Hey i was here to day playing around with interfaces to try get better to them (cos i never use anything but abstract classes cos i never feel interfaces is much of use) but i have made the following code:

class Program
    {
        static void Main(string[] args)
        {
            List<maintestclass> tl = new List<maintestclass>() { new testclass(), new testclass(), new testclass2()};
            List<testinterface> ti = new List<testinterface>();

            Console.ReadLine();
        }
    }

    public class testclass : maintestclass, testinterface
    {
        public void testmetode()
        {
            Console.WriteLine("interface call");
        }
    }

    public class testclass2 : maintestclass
    {
    }

    public abstract class maintestclass
    {

    }

    public interface testinterface
    {
        void testmetode();
    }



而我真正想做的是解析"tl"中可以从testinterface继承到ti的每个对象,但看来我无法使其正常工作,我试图使用"where"并获取类型,但是找不到有用的对象.方式...

如果有人斋戒可以帮助我,我会很高兴. (示例代码会很有帮助)

-Jackie



and what i really wanna do is to parse every object in "tl" that can inherit from testinterface to ti but it seems i cant make it to work, i''ve tried to use "where" and get type but cant find a usefull way to do it...

if anyone fast could help me i would be greatfull. (sample codes would help alot)

- Jackie

推荐答案

如果我理解正确,则可以将对象实例投射到您的界面上,例如:

If I understood correctly, you can cast an object instance to your interface like:

testinterface someVar = originalVar as testinterface;


之后,如果原始实例实现了该接口,则someVar应该包含该变量作为您的接口.如果没有,则someVar为null.


after that someVar should contain the variable as your interface if the original instance implemented the interface. If it didn''t, someVar is null.


这篇关于将类解析为可以继承的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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