gpt4 book ai didi

.net - Powershell 和覆盖比较运算符

转载 作者:行者123 更新时间:2023-12-04 21:54:55 26 4
gpt4 key购买 nike

如何创建一个对象,当它的操作符时,例如:

operator > (Object obj1, Object obj2)  
operator < (Object obj1, Object obj2)

,被覆盖的 PowerShell 是否利用了这些运算符?

这样:
where-object { $CustomObject -gt 12 } 

会打电话:
public static bool operator > (Object object1, Object object2)

是否可以?

澄清:
  • 对象存在于 .NET 程序集中
  • 对象已覆盖比较运算符
  • PowerShell 似乎不尊重这些运算符
  • 最佳答案

    PowerShell 使用 IComparable 接口(interface)来比较对象。至少,这是以下小实验所显示的:

    $src = @'
    using System;
    namespace Acme
    {
    public class Foo : IComparable
    {
    public Foo(int value)
    {
    this.Value = value;
    }

    public int Value { get; private set; }

    public static bool operator >(Foo foo1, Foo foo2)
    {
    Console.WriteLine("In operator >");
    return (foo1.Value > foo2.Value);
    }

    public static bool operator <(Foo foo1, Foo foo2)
    {
    Console.WriteLine("In operator <");
    return (foo1.Value < foo2.Value);
    }

    public int CompareTo(object obj)
    {
    Console.WriteLine("In CompareTo");
    if (obj == null) return 1;

    Foo foo2 = obj as Foo;
    if (foo2 == null) throw new ArgumentException("Not type Foo","obj");

    if (this.Value == foo2.Value)
    {
    return 0;
    }
    else if (this.Value > foo2.Value)
    {
    return 1;
    }
    else
    {
    return -1;
    }
    }
    }
    }
    '@

    Add-Type -TypeDefinition $src -Language CSharpVersion3

    $foo1 = new-object Acme.Foo 4
    $foo2 = new-object Acme.Foo 8

    $foo1 -gt $foo2
    In CompareTo
    False

    关于.net - Powershell 和覆盖比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2030014/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com