在 C# 中散列一个委托函数

Noa*_*oah 4 c# hash delegates

如何在 C# 中获取委托函数的哈希值。我希望能够判断是否将不同的代表发送到我的函数中。我的代码看起来像这样:

public string GetContent(Func<string, bool> isValid)
{
// Do some work
SomeFunctionToHashAFunction(isValid)
}
Run Code Online (Sandbox Code Playgroud)

我会使用 .GetHashCode() 但 .NET 框架不保证这些将是唯一的。

编辑 我有一些正在验证的缓存内容,但我只想验证一次。但是,如果验证功能发生变化,那么我需要重新验证缓存的内容。我不确定 ObjectIdGenerator 是否可以在这个实例中工作,因为我需要确定两个匿名函数是否具有相同的实现。

Ken*_*art 5

根据定义,散列不能保证是唯一的,所以散列不是你想要的。

相反,您想确定之前是否“见过”了委托的实例。为此,您可以使用ObjectIdGenerator

private static readonly ObjectIdGenerator oidg = new ObjectIdGenerator();

public string GetContent(Func<string, bool> isValid)
{
    bool firstTime;

    oidg.GetId(isValid, out firstTime);

    if (!firstTime)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,即使使用这种技术,也有一些陷阱需要注意:

  • ObjectIdGenerator 存储对传递给它的每个对象的引用
  • 同一函数的委托是不同的对象,因此会返回不同的 ID

也许如果你解释你想要达到的目标,可能会有更好的方法来实现它。

编辑:鉴于您更新的要求,我只是将验证委托定义为一个属性。如果属性发生变化,您就知道需要重新验证。GetContent()因此不需要任何参数:

public Func<string, bool> IsValidHandler
{
    get { return this.isValidHandler; }
    set 
    {
        this.isValidHandler = value;
        this.requiresValidation = true;
    }
}

public string GetContent()
{
    if (this.requiresValidation && this.isValidHandler != null)
    {
        // do validation

        this.requiresValidation = false;
    }

    // return content
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以进一步简化并在IsValidHandler设置属性时(不在GetContent方法中)进行验证。