通用方法如何工作?

Eri*_*ppe 1 c# generics

我最近在MSDN上学习了这个教程,允许我的应用程序用户更改和保存设置.经过一番头疼之后我觉得我理解了所有这一切,除了一件事.让我们从原始代码中最相关的部分开始.一切都在一个名为AppSettings的类中.我用来测试它的属性是son1.我的理解是这样的:

在代码的最后,你得到了这个:

 // Property to get and set son1 Key.
    public int son1
    {
        get
        {
            return GetValueOrDefault<int>(son1KeyName, son1Default);
        }
        set
        {
            if (AddOrUpdateValue(son1KeyName, value))
            {
                Save();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果你设置了属性,那很简单.它只是调用这个方法:

public bool AddOrUpdateValue(string Key, Object value)
    {
        bool valueChanged = false;
 // If the key exists
        if (settings.Contains(Key))
        {
            // If the value has changed
            if (settings[Key] != value)
            {
                // Store the new value
                settings[Key] = value;
                valueChanged = true;
            }
        }
        // Otherwise create the key.
        else
        {
            settings.Add(Key, value);
            valueChanged = true;
        }
        return valueChanged;
    }
Run Code Online (Sandbox Code Playgroud)

我必须这样做而且我已经完成了:

AppSettings param = new AppSettings();
        param.son1 = 1;
Run Code Online (Sandbox Code Playgroud)

现在GET的语法对我来说似乎更奇怪.过程是相同的,属性使用方法.get属性列在我的帖子顶部.如您所见,它调用此方法:

public T GetValueOrDefault<T>(string Key, T defaultValue)
    {
        T value;

        // If the key exists, retrieve the value.
        if (settings.Contains(Key))
        {
            value = (T)settings[Key];
        }
        // Otherwise, use the default value.
        else
        {
            value = defaultValue;
        }
        return value;
    }
Run Code Online (Sandbox Code Playgroud)

我对"T"感到不安,"T"也写在<和>之间.如果我能理解它,我应该能够将属性设置为默认值,我可以在我的程序开始时做.任何小费都表示赞赏.谢谢.

Jon*_*eet 6

我对"T"感到不安,"T"也写在<和>之间.

这表明它是一种通用方法.

基本上,你不会明白它不读有关仿制药,这是远远太大,以堆栈溢出的回答充分涵盖的话题.按照MSDN指南的链接:)

非常简短的版本是,这意味着所述方法由一个参数类型以及由值.泛型可以应用于类型和方法,因此a List<string>是"字符串列表",a List<int>是"整数列表".通用方法类似,但稍微难以理解 - 这里GetValueOrDefault可以描述为"返回T基于给定字符串键的类型值 - 或者T如果设置中不存在键,则返回提供的默认值(也是类型) ".

因此,GetValueOrDefault<string>(key, "foo")将从string设置返回a ,默认为"foo",并将从设置GetValueOrDefault<int>(key, 10)返回int,默认为10.

这只是30秒的步行通过 - 还有很多东西需要学习:)