相关疑难解决方法(0)

"as"和可空类型的性能惊喜

我刚刚修改了深度C#的第4章,它处理了可空类型,我正在添加一个关于使用"as"运算符的部分,它允许你编写:

object o = ...;
int? x = o as int?;
if (x.HasValue)
{
    ... // Use x.Value in here
}
Run Code Online (Sandbox Code Playgroud)

我认为这非常简洁,它可以提高性能而不是C#1等效,使用"is"后跟一个演员 - 毕竟,这样我们只需要请求动态类型检查一次,然后进行简单的值检查.

然而,情况似乎并非如此.我在下面包含了一个示例测试应用程序,它基本上对对象数组中的所有整数求和 - 但该数组包含许多空引用和字符串引用以及盒装整数.该基准测试您必须在C#1中使用的代码,使用"as"运算符的代码,以及用于踢LINQ解决方案的代码.令我惊讶的是,在这种情况下,C#1代码的速度提高了20倍 - 即使是LINQ代码(考虑到所涉及的迭代器,我预计它会更慢)也胜过"as"代码.

可以isinst为空的类型的.NET实现真的很慢吗?是unbox.any导致问题的附加因素吗?还有另一种解释吗?目前,我觉得我必须在性能敏感的情况下包含警告,禁止使用它...

结果:

演员:10000000:121
As:10000000:2211
LINQ:10000000:2143

码:

using System;
using System.Diagnostics;
using System.Linq;

class Test
{
    const int Size = 30000000;

    static void Main()
    {
        object[] values = new object[Size];
        for (int i = 0; i < Size - 2; i += 3)
        {
            values[i] = null;
            values[i+1] …
Run Code Online (Sandbox Code Playgroud)

c# clr performance unboxing nullable

326
推荐指数
10
解决办法
3万
查看次数

C#接口定义了多个功能

有人可以帮助我理解为什么这不起作用:

public interface IInterface
{
    string GetString(string start);
    void DoSomething();
}

public class InterfaceImpl : IInterface
{
    string IInterface.GetString(string start)
    {
        return start + " okay.";
    }
    void IInterface.DoSomething()
    {
        Console.WriteLine(this.GetString("Go")); // <-- Error: InterfaceImpl does not contain a definition for GetString
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么我不能调用在实现中最明确定义的函数.

谢谢你的帮助.

c# interface

0
推荐指数
2
解决办法
75
查看次数

GetEnumerator在此上下文中不存在

我已经实现了一个自定义链表,我在实现IEnumerator <>时遇到了问题.具体来说,编译器告诉我The name "GetEnumerator" does not exist in the current context.我觉得我正在实现它,正如我在众多stackoverflow帖子和教程中看到的那样,我错过了什么?

这是我的数据结构:

namespace TestReportCreator_v3
{
    public class FindingsTable : IEnumerable<string>
    {
        private Node head, mark;
        public class Node
        {
            public string description; //covers weakness, retinaDesc, nessusDesc
            public string riskLevel; //covers impactLevel, retinaRisk, nessusRisk
            public string boxName; //box name results apply to
            public string scanner; //wassp, secscn, retina, nessus
            public string controlNumber; //ia control number impacted, wassp and secscn only
            public string fixAction; //comments, retinaFix, nessusSolu
            public string auditID; …
Run Code Online (Sandbox Code Playgroud)

c# ienumerable ienumerator linked-list

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