小编use*_*670的帖子

如何在C#中获得C++的"const"等价物?

在C++中,如果我想在编译时初始化一个对象并且之后永远不会改变,我只需添加前缀const.

在C#中,我写道

    // file extensions of interest
    private const List<string> _ExtensionsOfInterest = new List<string>()
    {
        ".doc", ".docx", ".pdf", ".png", ".jpg"
    };
Run Code Online (Sandbox Code Playgroud)

并得到错误

除string之外的引用类型的const字段只能用null初始化

然后我研究了Stack Overflow上的错误,并提出了"解决方案" ReadOnlyCollection<T>.除字符串之外的引用类型的const字段只能使用null Error初始化

但这并没有真正给我我想要的行为,因为

    // file extensions of interest
    private static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>()
    {
        ".doc", ".docx", ".pdf", ".png", ".jpg"
    };
Run Code Online (Sandbox Code Playgroud)

仍然可以重新分配.

那么我该怎样做我想做的事情呢?

(令人惊讶的是,除了我想要的语言之外,C#还具有所有语言功能的可模仿性.

c#

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

异步 - 等待在我的程序中并行运行两个独立任务的必要条件吗?

我将尝试用你在下面看到的毫无意义的例子来说明我的问题.

using System;
using System.IO;
namespace PointlessProgram
{
    class PointlessClass 
    {
        public static void WriteFooToTextFile ( )
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Hillary\Documents\PointlessFolder\Foo.txt"))
            {
                file.Write("Foo");
            }
        }

        public static void WriteBarToTextFile ( )
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Hillary\Documents\PointlessFolder\Bar.txt")) 
            {
                file.Write("Bar");
            }    
        }

        static void Main() 
        {
           WriteFooToTextFile(); // (A)
           WriteBarToTextFile(); // (B)    
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,(B)不需要运行,(A)因为它不依赖于产生的任何输出(A),并且更好(A)依赖于(B).假设我的计算机有2个处理器,并且会将所有处理能力用于运行该程序.编译器是否会找出(A)并且(B)可以并行运行,或者它会一个接一个地运行它们除非我明确地编写我的代码以告诉机器(A)在开始执行之前不等待完成(B)?如果是这样,是async- await …

.net c# parallel-processing asynchronous async-await

2
推荐指数
1
解决办法
477
查看次数

这种设计模式实现了什么?

我试图弄清楚我的书中的代码示例是什么.它说

在外部异常处理程序的try-catch块中添加内部块finally以防止丢失异常信息:

private void PreventLossOfExeptionFormat()
{
   try
   {
       // ... 
   }
   catch(Exception e)
   {
       Console.WriteLine("Error message == " + e.Message);
       throw;
   }
   finally
   {
       try
       { 
          // ...
       }
       catch(Exception e)
       {
           Console.WriteLine("An unexpected error occured in the finally block. Error message: " + e.Message);
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

外部异常如何进入内部异常?据我所知,在外部catch块它越来越扔进finally块,但它然后得到立即陷入catch了的finally块或什么点try里面呢?因为如果已经有异常提出那么就没有try...

.net c#

2
推荐指数
1
解决办法
58
查看次数

Array.prototype.reduce的实际用途是什么?

据我所知,这是一种具有广泛适用性的常用功能.Mozilla开发网络例子

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue + currentValue;
});
Run Code Online (Sandbox Code Playgroud)

它具有对值进行求和的效果.当然,这不是一个很好的例子,因为他们不能做到[0, 1, 2, 3, 4].sum().

那么现实生活中的情况是,作为一名网络开发人员,我将面临一个问题并思考," 啊,这是一个工作reduce! "要么是一个非常模糊的情况,要么是一个我可以reduce用作一个常见的情况巧妙的解决方法.

javascript

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

如何将2-D C#数组初始化为所有相同的值?

我想做的事情在下面的评论中描述.我怎么能有效率地做?

using System;
using System.Collections.Generic;
using System.IO;
class Solution {
    static void Main(String[] args) {
        int n = Int32.Parse(Console.ReadLine());
        bool[][] flags = new bool[26][n]; // I want this to be a 26 x n array of false values
        for(int k = 0; k < n; ++k)
        {
            string line = Console.WriteLine();
            for(int i = 0; i < line.Length; ++i)
                flags[(int)line[i] - (int)'a'] = true;
        }
        int gems = flags.Count(arr => arr.Count(j => j == true) == arr.Length);       
        Console.WriteLine
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# arrays algorithm data-structures

1
推荐指数
2
解决办法
171
查看次数

我需要帮助理解LINQ.我的理解在哪里出错了?

我会尽力帮助你理解它,你让我知道我哪里出错了.

为简单起见,我们假设我们生活在一个只有的词中

  • 数字1,2,3,4,5
  • 运营商%,>他们通常的预防

我想解释当我这样做时会发生什么

List<int> All = new List<int> { 1, 2, 3, 4, 5 };
IEnumerable<int> Filtered = from i in All
                            where i % 2 == 1
                            orderby i descending
                            select i; 
foreach ( var i in Filtererd ) 
{
   Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)

我首先理解的是查询本身并没有创建Ienumerable<int>; 它创建与查询关联的表达式树.查询返回的元素yield在编译器创建的不可见函数中编辑

public static IEnumerable<int> MyInvisibleFunction ( List<int> Source )
{
    foreach ( int i in …
Run Code Online (Sandbox Code Playgroud)

.net c# linq

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

为什么我在这里得到IndexOutOfRangeException?

我无法弄清楚为什么我会在Where下面的条款中得到它.

using System;
using System.Linq;

public static class Extensions
{
    /// <summary>
    /// Removes consecutive characters,
    /// e.g. "aaabcc" --> "abc"
    /// </summary>
    public static void RemoveDuplicates(this string s)
    {
        var arr = s.ToCharArray()
                   .Where((i,c) => (i > 0) ? (c != s[i - 1]) : true)
                   .ToArray();
        s = new string(arr);

    }
}


public class Program
{   
    public static void Main()
    {
        var str = "aaabcc";
        str.RemoveDuplicates();
        Console.WriteLine(str);
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,还有一种方法可以在使用LINQ的同时使其更加高效和紧凑吗?

c# linq algorithm

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

我是否正确的基本git命令如何?

我正在尝试理解git,我想知道你是否可以在我在下面的例子中做出的任何错误的观点上纠正我.

举个简单的例子,假设我初始化一个包含以下2个简单文件的存储库.

main.cpp中

#include <stdio.h>

int main()
{
  printf("Hello world\n");
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

algorithms.cpp

#include <string.h>   
void reverse_string ( char * s ) 
{
   char * offend = *(s + strlen(s));
   while(offend != s && --offend != s)
   {
      char temp = *s;
      *s = *offend;
      *offend = temp;
      ++s;
   }
}
Run Code Online (Sandbox Code Playgroud)

当我commitadd所有文件之后创建第一个文件时,2个文件的内容存储在git中,然后我返回一个根据2个文件的内容计算的哈希值(加上一些元数据,例如它们在目录树中的位置和等等).该散列仅仅是一个标识符,但也可以用于检查不同的提交是否包括相同的文件集(假设散列中没有冲突).我们假设哈希是firstcommit5njn2n34n.

现在我已经进行了第一次提交,base除非我rebase在某个时刻,否则它将用于所有后续提交.

假设我对第二个文件稍作修改.

algorithms.cpp

#include <string.h>   
void reverse_string ( char * s ) 
{
   char * offend = …
Run Code Online (Sandbox Code Playgroud)

svn git version-control github

-1
推荐指数
1
解决办法
63
查看次数

如何在C#中编写最佳Swap(T a,T b)算法?

我在这个孤独的星期五晚上的任务是写一个C#交换算法

public void Swap<T> ( ref T a, ref T b ) 
{
   // ... 
} 
Run Code Online (Sandbox Code Playgroud)

适用于任何类或数据类型T,并尽可能高效.帮助批评我到目前为止建立的方法.首先,这是正确的吗?我如何才能使其获得Skeet认证?

public void Swap<T> ( ref T a, ref T b ) 
{
   // Not sure yet if T is a data or value type. 
   // Will handle swapping algorithm differently depending on each case.
   Type type = T.GetType();
   if ( (type.IsPrimitive()) || (type == typeof(Decimal)) )
   {
       // this means the we can XOR a and b, the fastest way of …
Run Code Online (Sandbox Code Playgroud)

.net c# algorithm optimization

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

这里的性能错误可能在哪里?

许多测试用例都是超时的.我已经确定我在任何地方使用懒惰的评估,线性(或更好)的例程等等.我很震惊,这仍然不符合性能基准.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Mine
{
    public int Distance { get; set; } // from river
    public int Gold { get; set; } // in tons
}

class Solution 
{
    static void Main(String[] args) 
    {
        // helper function for reading lines
        Func<string, int[]> LineToIntArray = (line) => Array.ConvertAll(line.Split(' '), Int32.Parse);

        int[] line1 = LineToIntArray(Console.ReadLine());
        int N = line1[0], // # of mines
            K = line1[1]; // # of pickup locations

        // Populate mine info …
Run Code Online (Sandbox Code Playgroud)

c# linq algorithm optimization performance

-5
推荐指数
1
解决办法
99
查看次数

在普通的C中,不使用strlen或任何使用strlen的库函数,如何找到一个字符串是否包含在另一个字符串中?

我说没有strlen用于效率目的.因为如果你使用strlen那么你已经迭代了一个字符串,最好的算法总是迭代一个给定的容器不超过一次.所以帮助我思考如何实现一个功能

bool contains ( char * s1, char * s2 ) 
{
   // ... 
}
Run Code Online (Sandbox Code Playgroud)

尝试:

bool contains ( char * s1, char * s2 ) 
{
   // returns true or false depending on whether s1 is contained in s2

   // define that every string contains the empty string
   if ( !*s1 ) return true;

   // search for substrings of s2 that equal s1
   bool flag = true;
   while ( *s2 ) 
   {
       char * c …
Run Code Online (Sandbox Code Playgroud)

c algorithm optimization

-6
推荐指数
1
解决办法
135
查看次数