如何从对象访问接口实现?
interface IGraphicsObject
{
Draw();
Delete();
}
我创建了3个类:Square
,Circle
和Triangle
,它们都实现了IGraphicsObject
。然后输入
object Shape = Activator.CreateInstance("myShapes", "Square");
然后我想键入:
Shape.Draw();
Shape.Delete();
等。
我该怎么做?
转换为IGraphicsObject
IGraphicsObject Shape = (IGraphicsObject)Activator.CreateInstance("myShapes", "Square");
现在使用创建的实例,您可以调用接口方法
Shape.Draw();
Shape.Delete();
简单的答案是对它进行类型转换,但您可以通过以下方式做得更好:
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();
}
}
因此,您可以确保只有实现该接口的类型才允许用于类型转换创建方法。