在C#中不继承静态方法的解决方法?

问题描述

我有几个从抽象类派生的类。我希望能够根据抽象静态属性(例如“ maxSpeed”)的值选择这些派生类之一,并为其创建一个实例。例如,如果我要求的速度为5,ClassA.maxSpeed为2,ClassB.maxSpeed为7,则客户端代码将创建Class B的实例。

C#不支持静态属性方法的继承,因此上述方案不起作用。有解决方法吗?

解决方法

您可以使用自定义属性:

/alldata

enter image description here

注意,如果该类没有无参数的构造函数,则此操作将失败。如果没有扩展using System; using System.Linq; using System.Reflection; namespace ConsoleApp10 { abstract class Abstract {} [MaxSpeed(10)] class ClassA : Abstract {} [MaxSpeed(20)] class ClassB : Abstract {} internal class MaxSpeedAttribute : Attribute { public int MaxSpeed { get; } public MaxSpeedAttribute(int maxSpeed) { MaxSpeed = maxSpeed; } } class Program { static void Main(string[] args) { var candidates = Assembly .GetExecutingAssembly() .GetTypes() .Where(t => t.IsSubclassOf(typeof(Abstract))) .Select(t => (type: t,maxSpeedAtt: t.GetCustomAttribute<MaxSpeedAttribute>())) .Where(t => t.maxSpeedAtt != null); var candidate = candidates.FirstOrDefault(c => c.maxSpeedAtt.MaxSpeed > 4); var myClass = (Abstract)Activator.CreateInstance(candidate.type); } } } 的类声明该属性,它也会失败。

请记住,如果您的类在其他程序集中,则需要扫描它们而不是Abstract

我将由您自己决定所需的选择逻辑。

,

感谢您的回复。我决定将静态属性(应为静态属性)更改为非静态,并在需要确定“ maxSpeed”时创建该类的实例。所以,代替 “ ClassA.maxSpeed”是“新的ClassA()。maxSpeed”。