gpt4 book ai didi

c# - System.TypeInitializationException : The type initializer for 'Tips' threw an exception

转载 作者:行者123 更新时间:2023-11-30 13:23:02 25 4
gpt4 key购买 nike

我正在尝试访问静态列表的值。但是,当我尝试这样做时,会抛出此异常。

System.TypeInitializationException: The type initializer for 'Tips' threw an exception. -- -> System.NullReferenceException: Object reference not set to an instance of an object

带有列表的类。

    public static class Tips
{
//private List<Tip> roadtips = new List<Tip>();
public static List<Tip> tips { get; set; }

static Tips()
{
tips.Add(new Tip("Don't use your mobile phone whilst driving", "Making or receiving a call, even using a 'hands free' phone, can distract your attention from driving and could lead to an accident. "));
tips.Add(new Tip("Children", "Children often act impulsively, take extra care outside schools, near buses and ice cream vans when they might be around."));
tips.Add(new Tip("Take a break", "Tiredness is thought to be a major factor in more than 10% of road accidents. Plan to stop for at least a 15 minute break every 2 hours on a long journey."));
tips.Add(new Tip("Don't drink and drive", "Any alcohol, even a small amount , can impair your driving so be a safe driver don't drive and drive."));
tips.Add(new Tip("Anticipate ", "Observe and anticipate other road users and use your mirrors regularly."));
tips.Add(new Tip("Use car seats ", "Child and baby seats should be fitted properly and checked every trip."));
tips.Add(new Tip("Keep your distance ", "Always keep a two second gap between you and the car in front."));
}
}

这是试图访问列表的类。

 public partial class tip : PhoneApplicationPage
{
public tip()
{
InitializeComponent();
Random r = new Random();
int rInt = r.Next(0, 6);
tipname.Text = Tips.tips[rInt].Name;
tipdesc.Text = Tips.tips[rInt].Description;
}
}

发生这种情况的原因是什么?有没有更好的方法来存储这些提示。我只需要一个提示列表来输出到 Windows Phone 页面上的两个文本 block 。

最佳答案

您似乎从未将自动实现的属性 tips 初始化为一个值。因此它是 null 并在您的静态初始化程序中导致异常。尝试初始化值

static Tips()
{
tips = new List<Tip>();
...
}

关于c# - System.TypeInitializationException : The type initializer for 'Tips' threw an exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15261332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com