【问题标题】:C# code using OpenTK使用 OpenTK 的 C# 代码
【发布时间】:2012-04-01 04:11:56
【问题描述】:

我刚开始学习 C# 和 OpenTK(我已经了解 Java 和 C++)。我在 OpenTK 提供的演示代码中遇到了这行代码:

if (Keyboard[Key.Escape])
            Exit();

如果 Esc 按钮被按下,Keyboard[Key.Escape] 将返回 true。但是,我不认识这种语法。键盘不是数组。谁能向我解释一下这种语法是什么以及它是如何工作的?参考链接就足够了。感谢您的宝贵时间。

【问题讨论】:

  • 这个概念只叫Indexer!!!

标签: c# opentk


【解决方案1】:

在 c# 中,任何对象都可以实现启用括号 [] 语法的索引属性,这就是这里发生的事情。以下是一个简单的示例——虽然它显然不是传统意义上的数组,但它仍然具有可用的索引器语法。在您的情况下,该属性看起来是一个布尔值:

class Foo
{
    private string _foo; 

    public Foo(string foo)
    {
        _foo = foo; 
    }

    public bool this[string foo]  // the indexer can be anything
    {
        get                  // the getter can work however the programmer wants
        {
            return _foo == foo;
        }
    }
}

可以这样使用:

        Foo f = new Foo("Hello World!");

        bool foo = f["Hello World!"]; // will return true

【讨论】:

    猜你喜欢
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多