c# – 在通用方法中使用“未分配的局部变量”

栏目: ASP.NET · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/4910687/use-of-unassigned-local-variable-in-a-generic-method
使用未分配的局部变量’model’.我收到了什么错误信息.它正确我说if(model == null).我不知道为什么它给我一个编译时错误..有人请帮助.
public static T TryGet<T>(string fileName) where T : new()
{
    T model;
    using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storageFile))
        {
            if (stream.Length > 0)
            {
                var serializer = new DataContractSerializer(typeof(T));
                model = (T)serializer.ReadObject(stream);
            }
        }
    }
    if (model == null)
    {
        model = new T();
    }
    return model;
}

正如错误所述,在编译器可以证明它已被赋值之前,您不能使用局部变量.

在您的情况下,如果您的if条件为false,则永远不会分配模型变量.

您可以通过首先为其分配初始值来解决问题:

T model = default(T);

请注意,如果T是结构类型,则model == null永远不会为真.

您应该将代码更改为

using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storageFile))
{
    if (stream.Length > 0)
    {
        var serializer = new DataContractSerializer(typeof(T));
        return (T)serializer.ReadObject(stream);
    } 
    else 
    {
        return new T();
    }
}

翻译自:https://stackoverflow.com/questions/4910687/use-of-unassigned-local-variable-in-a-generic-method


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

深度探索Linux操作系统

深度探索Linux操作系统

王柏生 / 机械工业出版社 / 2013-10-15 / 89.00

《深度探索linux操作系统:系统构建和原理解析》是探索linux操作系统原理的里程碑之作,在众多的同类书中独树一帜。它颠覆和摒弃了传统的从阅读linux内核源代码着手学习linux操作系统原理的方式,而是基于实践,以从零开始构建一个完整的linux操作系统的过程为依托,指引读者在实践中去探索操作系统的本质。这种方式的妙处在于,让读者先从宏观上全面认清一个完整的操作系统中都包含哪些组件,各个组件的......一起来看看 《深度探索Linux操作系统》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具