如何以编程对象转换在运行时? [英] How to cast an object programmatically at runtime?

查看:110
本文介绍了如何以编程对象转换在运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一样的自定义控件:

Suppose I have a custom control like:

MyControl : Control

如果我有code是这样的:

if I have code like this:

List<Control> list = new ...
list.Add (myControl);

RolloutAnimation anim = list[0];

我知道我可以在编译时做,但我想这样做在运行时和访问MyControl特定的功能。

I know I can do it at compile time but I wanna do it at runtime and access MyControl specific functionality.

推荐答案

你为什么要在运行时做呢?如果您有更多类型的列表控件中,有一些特定的功能,但不同类型的,或许他们应该实现一个共同的接口:

Why do you want to do it at runtime? If you have more types of Controls in your List, that have some specific functionality, but different types, perhaps they should implement a common interface:

interface MyControlInterface
{
    void MyControlMethod();
}

class MyControl : Control, MyControlInterface
{
    // Explicit interface member implementation:
    void MyControlInterface.MyControlMethod()
    {
        // Method implementation.
    }
}

class MyOtherControl : Control, MyControlInterface
{
    // Explicit interface member implementation:
    void MyControlInterface.MyControlMethod()
    {
        // Method implementation.
    }
}


.....

//Two instances of two Control classes, both implementing MyControlInterface
MyControlInterface myControl = new MyControl();
MyControlInterface myOtherControl = new MyOtherControl();

//Declare the list as List<MyControlInterface>
List<MyControlInterface> list = new List<MyControlInterface>();
//Add both controls
list.Add (myControl);
list.Add (myOtherControl);

//You can call the method on both of them without casting
list[0].MyControlMethod();
list[1].MyControlMethod();

这篇关于如何以编程对象转换在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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