C#接口实现中的不同类型
我真的很难为此努力,但我会尽力解释自己的观点。
说我有这个:
List<IShape> Shapes = new List<IShape>();
public interface IShape {
dynamic shapeAttributes { get; set; }
};
public struct SquareAttributes {
float sizeOfSide;
};
public struct CircleAttributes {
float radius
};
public class Square : IShape {
SquareAttributes shapeAttributes { get; set; }
};
public class Circle : IShape {
CircleAttributes shapeAttributes { get; set; }
};
Shapes.Add(new Square());
Shapes.Add(new Circle());
如何使这种情况起作用?在这里,在Square和Circle实现时,Ishape中的“动态”关键字无法解决,但是我仍然希望能够在实现时定义正确的类型,而不是到处使用“动态”。是否有正确的方法可以处理同一列表中的各种形状的能力?我希望这很清楚。
我显然简化了整个过程,以直接达到这一点,但是所涉及的所有内容都更加复杂,无法真正安装成一个大型件。
I really struggle entitling this, but i'll try my best at explaining my point.
Say i have this :
List<IShape> Shapes = new List<IShape>();
public interface IShape {
dynamic shapeAttributes { get; set; }
};
public struct SquareAttributes {
float sizeOfSide;
};
public struct CircleAttributes {
float radius
};
public class Square : IShape {
SquareAttributes shapeAttributes { get; set; }
};
public class Circle : IShape {
CircleAttributes shapeAttributes { get; set; }
};
Shapes.Add(new Square());
Shapes.Add(new Circle());
How Do I make that situation work ? Here the "dynamic" keyword in IShape is not resolved when implemented in Square and Circle, but I'd still want to be able to define the right Type when implementing rather than using "dynamic" everywhere. Is there a right way to deal with this, with the ability re regroup all kind of Shapes in the same list? I hope this is clear.
I obviously simplified the whole thing to get straight to the point, but everything involved is far more complex and cannot really be fitted into a single large piece.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的形状属性截然不同,则可以将
system.Object
用作公共类型。但是,不要忘记检查您是否通过正确的shapeAttributes
键入以纠正ishape
的实现,因此我建议使用设置方法代替属性设置器:对象定义:
用法示例:
If your shapes attributes very different you can use
System.Object
as common type. But don't forget to check if you pass correctShapeAttributes
type to correct implementation ofIShape
, so I recommend to use set method instead of property setter:Objects definition:
Usage example: