小编nul*_*ull的帖子

为什么不能推断出这种通用Clamp方法的类型?

我正在写一个代表LED的课程.基本上uintr,g和b的3个值在0到255的范围内.

我是C#的新手,从uint 1开始,这比我想要的大8位.在编写我自己的Clamp方法之前,我在网上找了一个,发现这个很棒的答案提示了一个扩展方法.问题是它无法推断出类型uint.为什么是这样?这段代码已经写完了uint.我必须明确给出类型以使其工作.

class Led
{
    private uint _r = 0, _g = 0, _b = 0;

    public uint R
    {
        get
        {
            return _r;
        }
        set
        {
            _r = value.Clamp(0, 255); // nope

            _r = value.Clamp<uint>(0, 255); // works
        }
    }
}

// https://stackoverflow.com/a/2683487
static class Clamp
{
    public static T Clamp<T>(this T val, T min, T max) where T : IComparable<T>
    {
        if (val.CompareTo(min) < 0) return min;
        else if (val.CompareTo(max) …
Run Code Online (Sandbox Code Playgroud)

c# generics extension-methods

15
推荐指数
3
解决办法
1163
查看次数

空的初始化器和结构体的初始化器之间有什么区别?

我遇到了一些与此类似的代码:

struct Struct
{
    int a;
    int b;
};

int main()
{
    struct Struct variable = { };   // ???
    variable.a = 4;
    variable.b = 6;
}
Run Code Online (Sandbox Code Playgroud)

这很奇怪.初始化ab可能在初始化器中发生(在花括号之间).但他们不是.保持这个= { }部分有什么意义?以下应该没问题吧?

struct Struct variable;
Run Code Online (Sandbox Code Playgroud)

或者是吗?是否有一个空的初始化器与任何不具有初始化器的方式不同?

我的小C手册说明了这一点

对于没有初始化器的变量:具有静态作用域的所有变量都隐式初始化为零(即所有字节= 0).所有其他变量都有未定义的值!

需要注意的是,这并没有明确提到structs. 什么时候没有初始化的条件满足了struct我做了以下测试:

#include <stdio.h>

struct Struct
{
    int a;
    int b;
};

int main()
{
    struct Struct foo = { };
    foo.a = 4;

    struct Struct bar; …
Run Code Online (Sandbox Code Playgroud)

c struct initializer

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

为什么我不能等待异步方法的返回值?

情况

我将raspberry pi设置为服务器,通过HTTP将json作为输入."API"允许设置连接到pi的LED.一切正常,我可以从浏览器发送请求,一切都很好.

到达时,响应需要一段时间.这就是我想要异步沟通的原因.

我在msdn上发现了这个问题,解释了它是如何完成的.

// Three things to note in the signature:
//  - The method has an async modifier. 
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer.
//  - The method name ends in "Async."
async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. …
Run Code Online (Sandbox Code Playgroud)

.net c# asynchronous async-await

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