简体   繁体   English

设置委托属性

[英]Setting a delegate property

    public class Red : CollisionClass
    {
        public CollisionChecker Algorithm; //this is a delegate that checks the collision
        public Red()
        {
            Algorithm = BaseAlgorithm; //PROBLEM, i dont know how to assign it correctly
        }
        public bool BaseAlgorithm(CollisionClass field)
        {
            return true;//in this method there will be an algorithm to check collision
        }
    }
    public delegate bool CollisionChecker(CollisionClass x,CollisionClass y);

in this script: there is a class called Red, which is a derived class from an abstract class called CollisionClass. 在此脚本中:有一个名为Red的类,它是从一个名为CollisionClass的抽象类派生的类。 the collision class can check whether its colliding with another derived class. 碰撞类可以检查其是否与另一个派生类发生冲突。 to do so, an algorithm delegate can be stored in the algorithm property, the idea is that if i ever make an expansion of this class, i can create new algorithms and store them in the property, but i don't know how to assign a method as a delegate to the property. 为此,可以将算法委托存储在algorithm属性中,其想法是,如果我扩展此类,则可以创建新算法并将其存储在属性中,但是我不知道如何分配作为该属性的委托的方法。

Thank you for reading my question 感谢您阅读我的问题

Your syntax is fine, but the method you are trying to assign to the delegate doesn't match the declaration of the delegate type. 您的语法很好,但是您尝试分配给委托的方法与委托类型的声明不匹配。

The CollisionChecker delegate is defined as taking two CollisionClass instances as parameters, and returning true. CollisionChecker委托定义为以两个CollisionClass实例作为参数,并返回true。 Your method ( BaseAlgorithm ) only accepts a single CollectionClass . 您的方法( BaseAlgorithm )仅接受单个CollectionClass

That being said, in this case, it sounds like you don't need to use delegates at all. 话虽如此,在这种情况下,听起来您根本不需要使用委托。 You could easily eliminate the delegate, and just make your method virtual , as this will allow you to override it in subclasses later, providing the same "expansion" mechanism you're trying to achieve here: 您可以轻松地消除委托,而只需将您的方法设置为virtual ,因为这将允许您稍后在子类中覆盖它,并提供您要在此处实现的相同“扩展”机制:

 public virtual bool Algorithm(CollisionClass field)
 {
     return true;
 }

With this, subclasses could override the Algorithm method (though I would consider a better name, such as Collides , etc) as needed. 这样,子类可以根据需要重写Algorithm方法(尽管我会考虑使用更好的名称,例如Collides等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM