首页 \ 问答 \ 为什么我得到这个NullReferenceException?(Why am I getting this NullReferenceException?)

为什么我得到这个NullReferenceException?(Why am I getting this NullReferenceException?)

我正在研究一个涉及一些自制的(de-)序列化代码的项目,并且我遇到了一些列表反序列化的问题。 下面的代码在第二行抛出一个NullReferenceException,即使var list不为空,并且在将鼠标悬停在它上面时,它会高兴地报告Count = 0

System.Collections.IList list = ((System.Collections.IList)obj);
list.Add(val);

我的变量被实例化有点奇怪,所以也许这有什么关系呢? 这是涉及的代码。

System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);

type是什么

System.Type.GetType("System.Collections.Generic.List`1[[Networking.Client, Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

任何帮助将非常感激 :)


I'm working on a project that involves some home-made (de-)serialization code, and I have run into some issues with the deserializing of a List. The following code is throwing a NullReferenceException on the second line, even though the var list is not null, and happily reports Count = 0 when hovering my mouse over it.

System.Collections.IList list = ((System.Collections.IList)obj);
list.Add(val);

My variables are being instantiated a bit weird, so maybe that has got something to do with it? This is the code involved.

System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type);

Where type is

System.Type.GetType("System.Collections.Generic.List`1[[Networking.Client, Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

Any help would be much appreciated :)


原文:https://stackoverflow.com/questions/583859
更新时间:2021-10-16 08:10

最满意答案

通过指定label参数来创建条形图的图例条目,与许多其他艺术家类似。

ax.bar(...., label="my label")
ax.legend()

这也在文档的第一个例子中显示

完整的例子:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

train_errors = [1,2,3,4,5]
val_errors = [2,1,4,2,3]
test_errors = [5,4,3,2,1]
X = list("ABCDE")

x1 = [i-0.2 for i in range(len(train_errors))]
x2 = [i for i in range(len(train_errors))]
x3 = [i+0.2 for i in range(len(train_errors))]

ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors")
ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors")
ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors")

ax.set_xticks(x2)
ax.set_xticklabels(X)

ax.legend()

ax.set_xlabel('Models')
ax.set_ylabel('RMSE')
ax.set_title('Regression Models Comparison')
plt.show()

在这里输入图像描述


A legend entry for a bar plot, similar to many other artists, is created by specifiying the label argument.

ax.bar(...., label="my label")
ax.legend()

This is also shown in the first example in the documentation.

Complete example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

train_errors = [1,2,3,4,5]
val_errors = [2,1,4,2,3]
test_errors = [5,4,3,2,1]
X = list("ABCDE")

x1 = [i-0.2 for i in range(len(train_errors))]
x2 = [i for i in range(len(train_errors))]
x3 = [i+0.2 for i in range(len(train_errors))]

ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors")
ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors")
ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors")

ax.set_xticks(x2)
ax.set_xticklabels(X)

ax.legend()

ax.set_xlabel('Models')
ax.set_ylabel('RMSE')
ax.set_title('Regression Models Comparison')
plt.show()

enter image description here

相关问答

更多
  • 您需要自己创建图例。 为此,创建一些未在图中显示的矩形(所谓的代理艺术家)。 #create legend handles = [Rectangle((0,0),1,1,color=c,ec="k") for c in [low,medium, high]] labels= ["low","medium", "high"] plt.legend(handles, labels) 完整的例子: import matplotlib.pyplot as plt import numpy as np from m ...
  • 关于python错误的好处是,它们通常可以从字面上理解并直接告诉你这个问题。 “TypeError”告诉你,你有一个类型的问题。 您可以打印类型: print(type(l1)) # print(type(l2)) # 现在,“只能将元组(不是”列表“)连接到元组”将告诉你不能将barcontainer添加到列表中。 简单解决方案:添加两个列表: myl=[l1]+l2 The good ...
  • 您可以使用ax1.get_legend_handles_labels()从第一ax1.get_legend_handles_labels()图中获取图例句柄和标签,然后在第二个子图上创建图例时使用它们。 从文档 : get_legend_handles_labels(legend_handler_map=None) 返回图例的句柄和标签 ax.legend()相当于: h, l = ax.get_legend_handles_labels() ax.legend(h, l) import numpy a ...
  • plt.legend()将隐含地调用ax的legend方法。 使用pyplot接口,你有时不清楚你正在处理哪个轴。 所以Matplotlib官方文档还建议使用ax方法 (面向对象的API)。 它给你更多的控制和定制。 plt.legend() will implicitly invoke the legend method of ax. Using the pyplot interface, you sometimes do not know explicitly which axes you are de ...
  • 通过指定label参数来创建条形图的图例条目,与许多其他艺术家类似。 ax.bar(...., label="my label") ax.legend() 这也在文档的第一个例子中显示 。 完整的例子: import matplotlib.pyplot as plt fig, ax = plt.subplots() train_errors = [1,2,3,4,5] val_errors = [2,1,4,2,3] test_errors = [5,4,3,2,1] X = list("ABCDE" ...
  • 该问题的代码绘制了3条线图。 但是,由于一条线需要两个点才能存在,并且只提供一个点( x=[0], y=[0] ),所以不会在画布上显示。 你有两个选择: 提供更多分数, ax.plot([0,2,3],[0,11,5]) 将该点的点显示为点, ax.plot([0],[0], marker="o") 命令plt.legend(loc="best")在图中放置一个图例。 如果你忽略它,就没有传说。 The code from the question draws 3 line plots. However, ...
  • 多行matplotlib文本的对齐方式由关键字参数multialignment (有关示例http://matplotlib.org/examples/pylab_examples/multiline.html,请参阅此处)。 因此,您可以将图例的标题文本居中,如下所示: l = plt.legend(['Lag ' + str(lag) for lag in all_x], loc='lower right', title='hello hello hello \n worl ...
  • 你需要替换plt.draw() plt.gcf().canvas.draw() 或者,如果你有一个数字句柄, fig.canvas.draw() 。 这是必需的,因为图例位置仅在绘制画布时确定,之前它只是位于相同的位置。 使用plt.draw()是不够的,因为绘制图例需要使用后端的有效渲染器。 You would need to replace plt.draw() by plt.gcf().canvas.draw() or, if you have a figure handle, fig.canva ...
  • 对于使用TextArea的解决方案,请参阅此答案 。 然后,您需要为TextArea的文本重新创建fontproperties。 因为在这里你想要在图例中准确显示你作为文本的符号,为一些文本对象创建图例处理程序的更简单的方法是将文本映射到TextHandler 。 TextHandler子类matplotlib.legend_handler.HandlerBase及其create_artists生成要在图例中显示的文本的副本。 然后需要为图例调整一些文本属性。 import matplotlib.pyplo ...
  • 避免尝试在轴外排列盒子的噩梦的一种解决方案是使用带有textcolor乳胶标签。 以下代码 import matplotlib matplotlib.use('ps') from matplotlib import rc rc('text',usetex=True) rc('text.latex', preamble=r'\usepackage{color}') import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot( ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)