具有在调用或函数add上提供的类型的通用委托

时间:2009-10-15 00:20:27

标签: c#

我要做的是能够做这样的事情

public class Class1
{
    public delegate CollsionType ValidateDelegate< T >(PlayerState<T> state, Vector2 position, CollsionType boundary);

    public static ValidateDelegate ValidateMove;

    public void AnotherFunction< T >(PlayerState< T > state)
    {
         //option1
         ValidateDelegate.Invoke<T>(state,SomeParameter,SomeParamter2)
    }
}

public class Class2<TypeIWant>
{
    public void SomeFunction
    {
        //option2
        Class1.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture)
    }
}

这里的技巧是在Class1中创建委托时我不知道类型T.当函数添加到委托或调用委托时,我只知道T.

3 个答案:

答案 0 :(得分:1)

你几乎就在那里 - 只需将Class1设为通用,并将委托通用:

public class Class1<T>
{
    public delegate CollsionType ValidateDelegate<T>(PlayerState<T> state, Vector2 position, CollsionType boundary);

    public static ValidateDelegate<T> ValidateMove;

    public void AnotherFunction<T>(PlayerState<T> state)
    {
         ValidateDelegate.Invoke<T>(state,SomeParameter,SomeParamter2)
    }
}

并指定类型参数两次 - 一次为类,一次为委托:

public class Class2
{
    public void SomeFunction()
    {
        Class1<TypeIWant>.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture)
    }
}

答案 1 :(得分:0)

我通过使我调用Class 2的函数静态(删除委托的需要)并将Class2的泛型类型传递给Class1中调用Class2函数的函数来解决问题。

这个问题仍然可以有更多有效答案。这个现在对我来说很有用,因为我能够使这个函数保持静态。如果不是这样的话,我仍然会陷入困境。我仍然对那些不需要函数为静态或Class1为Generic的答案感兴趣,因为这会为我的项目打开一些选项。

答案 2 :(得分:0)

这是我能得到的最接近我问题的正确答案。我承认它违反了一些编码标准(因为它使用后期绑定),但似乎有用。

公共类Class1

{

public delegate CollsionType ValidateDelegate< T >(PlayerState<T> state, Vector2 position, CollsionType boundary);

public static Object ValidateMove;

public void AnotherFunction< T >(PlayerState< T > state)
{
     ValidateDelegate<T> ValFunction = (ValidateDelegate<T>)ValidateMove; 
     ValFunction.Invoke<T>(state,SomeParameter,SomeParamter2);
}

}

公共类Class2

{

public void SomeFunction
{

    Class1.ValidateMove = new ValidateDelegate<TypeIWant>(functionThatHasCorrectSigniture)
}

}