gpt4 book ai didi

PowerShell 方法重载解析错误?

转载 作者:行者123 更新时间:2023-12-03 06:45:11 24 4
gpt4 key购买 nike

PowerShell方法重载解析系统似乎与C#不一致

我们来比较一下

C#

class Program
{
static void Main(string[] args)
{
MyClass.MyMethod(false, DateTime.Now);
}
}

public static class MyClass
{
public static void MyMethod(object obj, DateTime dateTime)
{
Console.WriteLine("MyClass.MyMethod(object obj, DateTime dateTime)");
}

public static void MyMethod(bool b, string str)
{
Console.WriteLine("MyClass.MyMethod(bool b, string str)");
}
}

对比

PowerShell

Add-Type `
@"
using System;

public static class MyClass
{
public static void MyMethod(object obj, DateTime dateTime)
{
Console.WriteLine("MyClass.MyMethod(object obj, DateTime dateTime)");
}

public static void MyMethod(bool b, string str)
{
Console.WriteLine("MyClass.MyMethod(bool b, string str)");
}
}
"@

[MyClass]::MyMethod($false, [DateTime]::Now)

C# 将返回

MyClass.MyMethod(object obj, DateTime dateTime)

我们的预期

但是 PowerShell 将返回

MyClass.MyMethod(bool b, string str)

如果我们想要调用正确的方法,我们必须更明确地了解我们想要调用的重载

[MyClass]::MyMethod([object] $false, [DateTime]::Now)

我认为这是 PowerShell 中的一个错误,而不是一个功能

以上代码已在 PowerShell 3 中测试

在 PowerShell 2 中情况更糟。我找不到调用适当重载的方法

即使这个也不起作用

 [MyClass]::MyMethod([object] $false, [DateTime] ([DateTime]::Now))

最佳答案

PowerShell 允许比 C# 更多的类型强制。例如,如果需要,PowerShell 会将 DateTime 强制转换为字符串(或者将 int 强制转换为 bool,或将字符串强制转换为 bool)。我怀疑重载解析是在第一个参数上找到直接类型匹配,然后注意到第二个参数可以被强制,并且没有一个重载完全匹配类型。也就是说,我碰巧同意你的观点。我希望看到 PowerShell 的成员重载解析变得更好。在这种情况下,我想说类型兼容性应该优先于类型强制。当然,将 bool 值放入对象引用中需要装箱,因此可能会降低该特定重载的得分。

考虑将此问题提交给 PowerShell 团队 http://connect.microsoft.com .

关于PowerShell 方法重载解析错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13084176/

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