相关疑难解决方法(0)

访问Modified Closure

string [] files = new string[2];
files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml";
files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml";

//Resharper complains this is an "access to modified closure"
for (int i = 0; i < files.Length; i++ )
{
    // Resharper disable AccessToModifiedClosure
    if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(),
    delegate(string name) { return name.Equals(files[i]); }))
         return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]);
    // ReSharper restore AccessToModifiedClosure
}
Run Code Online (Sandbox Code Playgroud)

虽然ReSharper抱怨这是"访问修改后的闭包",但上述情况似乎工作正常.任何人都可以阐明这一点吗?

(这个主题在这里继续)

c# resharper closures

310
推荐指数
2
解决办法
8万
查看次数

C#反模式

简而言之:我发现Java反模式是不可或缺的资源.适合初学者和专业人士.我还没有为C#找到这样的东西.所以我将这个问题作为社区维基开放,并邀请所有人分享他们对此的了解.由于我是C#的新手,我对此很感兴趣,但不能从一些反模式开始:/

以下是我发现C#而不是其他语言的答案.

我只是复制/粘贴这些!考虑看看这些评论.


投掷 NullReferenceException

抛出错误的异常:

if (FooLicenceKeyHolder == null)
    throw new NullReferenceException();
Run Code Online (Sandbox Code Playgroud)

属性与公共变量

类中的公共变量(改为使用属性).

除非该类是一个简单的数据传输对象.


不理解bool是一个真正的类型,而不仅仅是一个约定

if (myBooleanVariable == true)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好

if (myBooleanVariable != false)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这样的结构通常使用CC++开发,其中一个布尔值的想法只是一个约定(0 ==假的,什么都为true); 在C#或其他具有真正布尔值的语言中,这不是必需的(或可取的).


运用 using()

没有using在适当的地方使用:

object variable;
variable.close(); //Old code, use IDisposable if available.
variable.Dispose(); //Same as close.  Avoid if possible use the using() { } pattern.
variable = null; //1. in release optimised away.  2. C# is …
Run Code Online (Sandbox Code Playgroud)

c# anti-patterns

55
推荐指数
21
解决办法
3万
查看次数

我在这个谓词链中缺少什么?

注意:在发布这个问题之前,我发现有一个更好的方法来做我想要完成的事情(我觉得它很愚蠢):

IEnumerable<string> checkedItems = ProductTypesList.CheckedItems.Cast<string>();
filter = p => checkedItems.Contains(p.ProductType);
Run Code Online (Sandbox Code Playgroud)

好的,是的,我已经意识到这一点.但是,无论如何,我发布了这个问题,因为我仍然不明白为什么我(愚蠢地)试图做的事情不起作用.


我觉得这很容易.原来它让我很头疼.

基本思路:显示ProductType在a中检查其属性值的所有项目CheckedListBox.

实施:

private Func<Product, bool> GetProductTypeFilter() {
    // if nothing is checked, display nothing
    Func<Product, bool> filter = p => false;

    foreach (string pt in ProductTypesList.CheckedItems.Cast<string>()) {
        Func<Product, bool> prevFilter = filter;
        filter = p => (prevFilter(p) || p.ProductType == pt);
    }

    return filter;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果在ProductTypesList(a CheckedListBox)中检查了"权益"和"ETF"项目.然后由于某种原因,以下代码仅返回"ETF"类型的产品:

var filter = GetProductTypeFilter();
IEnumerable<Product> filteredProducts = allProducts.Where(filter);
Run Code Online (Sandbox Code Playgroud)

我猜想它可能与一些自我引用的混乱有关filter,其本质上是本身 …

.net c# linq delegates predicate

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

使用Parallel Linq Extensions结合两个序列,如何才能首先产生最快的结果?

假设我有两个序列返回整数1到5.

第一个返回1,2和3非常快,但4和5每个需要200ms.

public static IEnumerable<int> FastFirst()
{
    for (int i = 1; i < 6; i++)
    {
        if (i > 3) Thread.Sleep(200);
        yield return i;
    }
}
Run Code Online (Sandbox Code Playgroud)

第二个返回1,2和3,延迟时间为200ms,但快速返回4和5.

public static IEnumerable<int> SlowFirst()
{
    for (int i = 1; i < 6; i++)
    {
        if (i < 4) Thread.Sleep(200);
        yield return i;
    }
}
Run Code Online (Sandbox Code Playgroud)

联合这两个序列只给出数字1到5.

FastFirst().Union(SlowFirst());
Run Code Online (Sandbox Code Playgroud)

我不能保证两种方法中的哪一种在什么时候有延迟,所以执行的顺序不能保证为我提供解决方案.因此,我想将联盟并行化,以便最小化我的例子中的(人为的)延迟.

一个真实场景:我有一个返回一些实体的缓存,以及一个返回所有实体的数据源.我希望能够从一个方法返回一个迭代器,该方法将请求内部并行化到缓存和数据源,以便缓存的结果尽可能快地生成.

注1:我意识到这仍然在浪费CPU周期; 我不是问我怎么能阻止序列迭代它们的慢元素,我怎么能尽可能快地结合它们.

更新1:我已经定制了achitaka-san对接受多个生成器的响应,并使用ContinueWhenAll将BlockingCollection的CompleteAdding设置为一次.我只是把它放在这里,因为它会因缺少注释格式而丢失.任何进一步的反馈都会很棒!

public static IEnumerable<TResult> SelectAsync<TResult>(
    params IEnumerable<TResult>[] producer)
{
    var resultsQueue = new BlockingCollection<TResult>();

    var taskList …
Run Code Online (Sandbox Code Playgroud)

.net c# parallel-processing parallel-extensions plinq

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

有人能用简单的术语解释C#中的"访问修改后的闭包"吗?

可能重复:
什么是'关闭'?
访问修改后的闭包
访问修改后的闭包(2)

Resharper抱怨下面这段代码:

foreach (string data in _dataList)
    DoStuff (() => field);
Run Code Online (Sandbox Code Playgroud)

什么是关闭?我为什么要关心?

我已经读过关于数学和函数式编程的闭包,我在这里不知所措.我的大脑太沉重了.

简单来说,这里发生了什么?

c# closures

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

多线程行为怪C#!

这是我的应用程序来执行线程示例,但输出不是预期的,任何人都有任何线索请

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace OTS_Performence_Test_tool
{
    class Program
    {

        static void testThread(string    xx)
        {

            int count = 0;
            while (count < 5)
            {
                Console.WriteLine(xx );
                count++;

            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Hello to the this test app ---");

            for (int i = 1; i<=3; i++)
            {

                    Thread thread = new Thread(() => testThread("" + i + "__"));

                thread.Start();

            }


            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是结果却是

3__

3__

3__

3__

3__

3__ …

c# multithreading

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

变量不明原因的增加

在我用于更改按钮设置的一个循环中,我还使用AddListener函数,而不是Inspector中的函数.我有5个项目,从0-4给出一系列"i",但是当我通过它应该调用的函数打印"i"时,它总是记录5,无论我按什么按钮,这都是奇怪的,因为"我"从来没有达到5.任何想法?

Ps我使用CustomEditor在检查器中显示2个按钮"预览布局"和"删除预览".

码:

using UnityEngine;
using System.Collections;
using UnityEditor;
using UnityEngine.UI;

public class RateMeManager : MonoBehaviour {

    public GameObject rateMeCanvas;
    public Sprite emptyStar, fullStar, button;
    public float spriteWidth, spriteHeight, spritePadding;

    [HideInInspector]
    public GameObject currentCanvas, tempButton;

    void Start () {
        RemovePreview();
        GenerateStars();
    }

    // Update is called once per frame
    public void GenerateStars () {
        RectTransform myRectTransform;
        if (currentCanvas != null)
        {
            GameObject temp;
            temp = currentCanvas;
            DestroyImmediate(temp);
        }
        currentCanvas = Instantiate(rateMeCanvas, Vector3.zero, Quaternion.identity) as GameObject;
        GameObject subCanvas = currentCanvas.transform.FindChild("subCanvas").gameObject;
        myRectTransform …
Run Code Online (Sandbox Code Playgroud)

c# custom-controls unity-game-engine

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