C# 从方法返回类型
如果我有一个返回 datagridview 的方法,并且流程与此类似:
if (ds.Tables.Count == 0)
{
SharedMethods.updateStatus("There are no excluded results to display");
//return dgv;
}
else
{
dgv.DataSource = ds.Tables[0];
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dgv.AllowUserToAddRows = false;
return dgv;
}
如果 if 条件为 true 那么我不想返回 datagridview(因为没有数据),在这种情况下我可以返回什么?如果我返回 null,则调用方法有一个 null datagridview,这会导致以后出现问题。
谢谢。
If I have a method that returns a datagridview and the flow is similar to this:
if (ds.Tables.Count == 0)
{
SharedMethods.updateStatus("There are no excluded results to display");
//return dgv;
}
else
{
dgv.DataSource = ds.Tables[0];
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dgv.AllowUserToAddRows = false;
return dgv;
}
If the if condition is true then I do not want to return a datagridview(as there is no data), what can I return in this case? If I return null, then the calling method has a null datagridview that causes later problems.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以
null
并向调用者添加对null
的特殊情况处理您通常将 3) 与
IEnumerables一起使用;
,但我不知道你的返回类型是否支持。如果您希望在第一种情况下表现得与查询没有结果一样,那么此解决方案是最好的。You can
null
and add special case handling fornull
to the callerYou usually use 3) with
IEnumerables<T>
, but I don't know if your return type supports it. This solution is best if you want your to behave the same way in your first case as if you got no results from your query.您可以设置方法的返回类型以返回错误代码 (
enum
) 并将DataGridView
作为out
或ref
参数。You could set the return type of the method to return an error code (
enum
) and have theDataGridView
as anout
orref
parameter.如果没有什么可显示的,只需将网格的 Visible 属性设置为 false 即可。
Just set the grid's Visible property to false if you have nothing to show.
在我看来,您有两种解决方案:
返回一个 null
DataGridView
并用它修改您的调用代码。返回一个
DataGridView
,但带有一个空的DataSource
(因为没有数据),并确保您的调用代码可以处理它。就我个人而言,我会选择 2。您仍然有一个视图,但没有数据,因此您仍然需要一个
DataGridView
,但它是空的。The way I see it you have two solutions:
Return a null
DataGridView
and modify your calling code with that.Return a
DataGridView
but with a nullDataSource
(as there's no data) and make sure your calling code can cope with that.Personally I'd go with 2. You still have a view but no data, so you still need a
DataGridView
but it's empty.我不会从数据绑定方法返回任何内容。你为什么需要那个? (此代码甚至无法编译,因为 true 块没有任何可返回的内容。)
只需将其设为一个方法即可。
I would not return anything from a data binding method. Why do you need that? (This code won't even compile because the true block has nothing to return.)
Simply make it a method.