gpt4 book ai didi

c# - 将运算符视为对象

转载 作者:行者123 更新时间:2023-12-02 05:31:51 25 4
gpt4 key购买 nike

我知道在 C# 中,作为混合语言,有运算符,它们不是对象,就像在 smalltalk 中一样。

有没有办法将它们视为对象(就像在 Smalltalk 中一样)?我的意思是,向它们添加属性和方法,或将它们包含在类层次结构中。

据我所知,(感谢 Google),有可能 overload an operator ,但我找不到其他任何东西。

例如,我想知道是否可以做类似的事情

if(+.PrecedenceLevel > *.PrecedenceLevel) 
{
//something
}

只是我的好奇心问题,与我的工作无关。

最佳答案

重载运算符是静态方法,因此有相应的 MethodInfo 对象可以被操作或调用:

var eqStr = typeof(string).GetMethod("op_Equality");
Console.WriteLine(eqStr.Name);//op_Equality - the .NET name rather than the C# name
Console.WriteLine(eqStr.IsSpecialName);//True - languages may give it a different name
Console.WriteLine(eqStr.Invoke(null, new object[]{"abc", "abc"}));//True
Console.WriteLine(eqStr.Invoke(null, new object[]{"abc", "def"}));//False

这实际上只是让我们了解该方法的语言中立特性,这可能很有用,但它不会让我们了解给定语言使用的名称(== 在 C# 中,=在 VB.NET 等中),它的优先级或任何可以说是“操作性”的东西。

而且它只用于重载,不用于内置。

关于c# - 将运算符视为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12251316/

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