相关疑难解决方法(0)

在从基类派生类的对象上调用时,“ this”关键字类型

如果我有这样的事情:

class Base
{
    public void Write()
    {
     if (this is Derived)
      {
         this.Name();//calls Name Method of Base class i.e. prints Base
        ((Derived)this).Name();//calls Derived Method i.e prints Derived 
      }
     else
      {
        this.Name();
      }
    }

    public void Name()
    {
        return "Base";
    }
}

class Derived : Base
{
    public new void Name()
    {
        return "Derived";
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用以下代码进行调用,

Derived v= new Derived();
v.Write(); // prints Base
Run Code Online (Sandbox Code Playgroud)

然后Name调用基类的方法。但是thisWrite方法中关键字的实际类型是什么?如果那是Derived类型(如Program控件在Write方法中输入第一个if块),则它正在调用基本Name方法,为什么显式强制(Derived)this转换将调用更改 …

c# inheritance method-hiding

3
推荐指数
1
解决办法
2179
查看次数

为什么C#!=运算符通过引用比较值类型?

我有以下代码返回false:

 private static bool AreRowsEqual(string[] fieldNames, DataRow row1, DataRow row2)
        {
            for (var i = 0; i <= fieldNames.Length - 1; i++)
            {
                if (row1[fieldNames[i]] != row2[fieldNames[i]])
                {
                    return false;
                }
            }
            return true;
        }
Run Code Online (Sandbox Code Playgroud)

这是令人惊讶的,因为只有一个long类型的字段被比较,并且每个字段的值根据即时窗口输出匹配:

?row1[fieldNames[i]];
34
?row2[fieldNames[i]];
34

?row1[fieldNames[i]].GetType();
{Name = "Int64" FullName = "System.Int64"}
    [System.RuntimeType]: {Name = "Int64" FullName = "System.Int64"}

? row2[fieldNames[i]].GetType();
{Name = "Int64" FullName = "System.Int64"}
    [System.RuntimeType]: {Name = "Int64" FullName = "System.Int64"}
Run Code Online (Sandbox Code Playgroud)

我在这里忽略了什么?在比较整数值时,我使用!=和=="无处不在".

c# operators

0
推荐指数
1
解决办法
126
查看次数

标签 统计

c# ×2

inheritance ×1

method-hiding ×1

operators ×1