我真的很難獲得這個權利,但我會盡力解釋我的觀點。
說我有這個:
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());
我如何使這種情況發揮作用?這里 IShape 中的“動態”關鍵字在 Square 和 Circle 中實作時沒有解決,但我仍然希望能夠在實作時定義正確的型別,而不是在任何地方使用“動態”。有沒有正確的方法來處理這個問題,能夠在同一個串列中重新組合所有型別的形狀?我希望這很清楚。
我顯然簡化了整個事情以直截了當,但所涉及的一切都復雜得多,不能真正放在一個大塊中。
uj5u.com熱心網友回復:
如果您的形狀屬性非常不同,您可以將System.Object
其用作常見型別。但是不要忘記檢查是否將正確ShapeAttributes
的型別傳遞給正確的實作IShape
,所以我建議使用 set 方法而不是屬性 setter:
物件定義:
public interface IShape
{
object ShapeAttributes { get; }
Type ShapeAttributesType { get; }
void SetAttributes(object shapeAttributes);
}
public class Square : IShape
{
public object ShapeAttributes { get; private set; }
public Type ShapeAttributesType => typeof(SquareAttributes);
public void SetAttributes(object shapeAttributes)
{
// Check if passed correct type
if (shapeAttributes.GetType() != ShapeAttributesType)
throw new ArgumentException($"Argument type must be {ShapeAttributesType.FullName}", nameof(shapeAttributes));
ShapeAttributes = shapeAttributes;
}
}
public class Circle : IShape
{
public object ShapeAttributes { get; private set; }
public Type ShapeAttributesType => typeof(CircleAttributes);
public void SetAttributes(object shapeAttributes)
{
// Check if passed correct type
if (shapeAttributes.GetType() != ShapeAttributesType)
throw new ArgumentException($"Argument type must be {ShapeAttributesType.FullName}", nameof(shapeAttributes));
ShapeAttributes = shapeAttributes;
}
}
public struct SquareAttributes
{
public float SizeOfSide { get; set; }
}
public struct CircleAttributes
{
public float Radius { get; set; }
}
使用示例:
List<IShape> shapes = new List<IShape>();
var square = new Square();
square.SetAttributes(new SquareAttributes()
{
SizeOfSide = 4.1f
});
var circle = new Circle();
circle.SetAttributes(new CircleAttributes()
{
Radius = 2.12f
});
shapes.Add(square);
shapes.Add(circle);
foreach (var shape in shapes)
{
//Cast ShapeAttributes based on owner class type
switch (shape)
{
case Square s:
var size = ((SquareAttributes)s.ShapeAttributes).SizeOfSide;
Console.WriteLine($"Square.ShapeAttributes.SizeOfSide = {size}");
break;
case Circle c:
var radius = ((CircleAttributes)c.ShapeAttributes).Radius;
Console.WriteLine($"Circle.ShapeAttributes.Radius = {radius}");
break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/490564.html
上一篇:將2個串列隨機分配到另外2個串列