【问题标题】:Accessing methods from interface after creating object from Activator.CreateInstance从 Activator.CreateInstance 创建对象后从接口访问方法
【发布时间】:2021-01-25 01:04:13
【问题描述】:

如何从对象访问接口实现?

interface IGraphicsObject
{
    Draw();
    Delete();
}

我创建了 3 个类:SquareCircleTriangle,它们都实现了 IGraphicsObject。然后我做类似的事情

object Shape = Activator.CreateInstance("myShapes", "Square");

然后我希望能够打字:

Shape.Draw();
Shape.Delete(); 

等等

我该怎么做?

【问题讨论】:

标签: c#


【解决方案1】:

投射到IGraphicsObject

IGraphicsObject Shape = (IGraphicsObject)Activator.CreateInstance("myShapes", "Square");

现在创建的实例,你可以调用接口方法

Shape.Draw();
Shape.Delete(); 

【讨论】:

    【解决方案2】:

    简单的答案是对它进行类型转换,但您可以通过以下方式做得更好:

        public interface IGraphicsObject
        {
            void Draw();
            void Delete();
        }
    
        public class Square : IGraphicsObject
        {
            public Square(string mysharpes, string square)
            {
            }
    
            // fill out...
        }
    
        public class Circle : IGraphicsObject
        {
            public Circle(string mysharpes, string square)
            {
            }
    
            // fill out...
        }
    
        public class Triangle : IGraphicsObject
        {
            public Triangle(string mysharpes, string square)
            {
            }
    
            // fill out...
        }
    
        public class Main
        {
            public IGraphicsObject CreateInstance<T>(string mysharpes, string square) where T : IGraphicsObject
            {
                return (IGraphicsObject) Activator.CreateInstance(typeof(T), mysharpes, square);
            }
    
            public void Run()
            {
                var shape1 = CreateInstance<Square>("mysharpes", "square");
                var shape2 = CreateInstance<Circle>("mysharpes", "square");
                var shape3 = CreateInstance<Triangle>("mysharpes", "square");
    
                Draw(shape1,shape2,shape3);
            }
    
            public void Draw( params IGraphicsObject[] shapes )
            {
                foreach( var shape in shapes )
                   shape.Draw();
            }
        }
    

    因此,您确保类型转换创建方法只允许实现接口的类型。

    【讨论】:

    • 抱歉,这很混乱。我最初的帖子是为了让我可以创建任何形状,任意次数,并且只需调用相同的方法来绘制或处理它的画布。直到用户点击它才知道它是什么形状
    • 是的,这也是您从我的回答中得到的。从 CreateInstance 返回的所有 3 个形状都可以在不知道任何对象类型的情况下使用 .Draw() 调用。
    猜你喜欢
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多