开发商!
我有一个非常奇怪的问题.我的项目有用C++编写的DLL和用C#编写的GUI.我已经实现了一些互操作性的回调.我计划在某些情况下C++ dll会调用C#代码.它有效...但不长,我不明白为什么.在C#部分注释中标记的问题
这里是简化示例的完整代码:
C++ DLL:
#include <SDKDDKVer.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
extern "C"
{
typedef void (*WriteSymbolCallback) (char Symbol);
WriteSymbolCallback Test;
_declspec(dllexport) void InitializeLib()
{
Test = NULL;
}
_declspec(dllexport) void SetDelegate(WriteSymbolCallback Callback)
{
Test = Callback;
}
_declspec(dllexport) void TestCall(const char* Text,int Length)
{
if(Test != NULL)
{
for(int i=0;i<Length;i++)
{ …Run Code Online (Sandbox Code Playgroud) 对于某些编程语言(例如C#,Javascript)而言,最让我困扰的是,尝试访问属性null会导致错误或异常发生.
例如,在以下代码段中,
foo = bar.baz;
Run Code Online (Sandbox Code Playgroud)
如果吧null,C#会引起讨厌NullReferenceException,我的Javascript解释器会抱怨Unable to get value of the property 'baz': object is null or undefined.
从理论上讲,我可以理解这一点,但在实际代码中我常常有一些深层对象,比如
foo.bar.baz.qux
Run Code Online (Sandbox Code Playgroud)
如果,在foo,bar或者baz为null之间,我的代码就会被破坏.:(此外,如果我在控制台中评估以下表达式,似乎有不一致的结果:
true.toString() //evaluates to "true"
false.toString() //evaluates to "false"
null.toString() //should evaluate to "null", but interpreter spits in your face instead
Run Code Online (Sandbox Code Playgroud)
我绝对鄙视编写代码来处理这个问题,因为它总是冗长,臭的代码.以下不是人为的例子,我从我的一个项目中抓取了这些(第一个是Javascript,第二个是C#):
if (!(solvedPuzzles &&
solvedPuzzles[difficulty] &&
solvedPuzzles[difficulty][index])) {
return undefined;
}
return solvedPuzzles[difficulty][index].star
Run Code Online (Sandbox Code Playgroud)
和
if (context != null &&
context.Request != null && …Run Code Online (Sandbox Code Playgroud) 我有水晶报告,一直说这个错误:
{"你调用的对象是空的."}
堆栈跟踪:
at CrystalDecisions.Windows.Forms.PageControl.OnMouseMove(MouseEventArgs e)
at System.Windows.Forms.Control.WmMouseMove(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.UserControl.WndProc(Message& m)
at CrystalDecisions.Windows.Forms.PageControl.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
at ADR.Forms.GALReport.GuardianAdLitemReport.btnPreviewReport() in C:\Users\user\Development\ProjectADR\ADR\Forms\CaseCoordinatorReports\GALReport\GuardianAdLitemReport.xaml.cs:line 527
at ADR.Forms.GALReport.GuardianAdLitemReport.Button_Click(Object sender, RoutedEventArgs e) in C:\Users\user\Development\ProjectADR\ADR\Forms\CaseCoordinatorReports\GALReport\GuardianAdLitemReport.xaml.cs:line 90
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, …Run Code Online (Sandbox Code Playgroud) 如何检查a DataTable是否从未设置过,这意味着它是Null或者Nothing?我的意思并不是空洞的DataTable.
例如:
Dim dt As DataTable = TryCast(Session("dt"), DataTable)
If dt.Rows.Count <> 0 Then
'Do something !
End If
Run Code Online (Sandbox Code Playgroud)
如果Session("dt")由于某种原因从未设置或在内存中丢失,dt.Rows.Count <> 0则会抛出此异常:
你调用的对象是空的.
寻找一些最佳实践指导.假设我有一行代码如下:
Color color = someOrder.Customer.LastOrder.Product.Color;
Run Code Online (Sandbox Code Playgroud)
Customer,LastOrder,Product和Color可以null在正常条件下.但是,如果路径中的任何一个对象为null,我希望color为null; 为了避免空引用异常,我需要检查每个对象的空条件,例如
Color color = someOrder == null ||
someOrder.Customer == null ||
someOrder.Customer.LastOrder == null ||
someOrder.Customer.Product == null ?
null : someOrder.Customer.LastOrder.Product.Color;
Run Code Online (Sandbox Code Playgroud)
或者我可以这样做
Color color = null;
try {color = someOrder.Customer.LastOrder.Product.Color}
catch (NullReferenceException) {}
Run Code Online (Sandbox Code Playgroud)
第一种方法显然有效,但编码和更难阅读似乎更乏味.第二种方法稍微容易一点,但对此使用异常处理可能不是一个好主意.
是否有另一种检查空值的快捷方式,并在必要时将null指定为颜色?或者在使用这种嵌套引用时如何避免NullReferenceExceptions的任何想法?
我想填写一个excel文件,所以我使用ExcelPackage:Office Open XML格式.但我有一个错误.我的代码:
string fileName = "DBE_BAKIM_FORMU" + ".xlsx";
FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("~/") + fileName);
using (ExcelPackage xlPackage = new ExcelPackage(fi))
{
ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
dbeDataContext db = new dbeDataContext();
CAGRI c = (from x in db.CAGRIs where x.CagriID == ID select x).SingleOrDefault();
USER u = (from x in db.USERs where x.UserID == Convert.ToInt32(Session["user"]) select x).SingleOrDefault();
worksheet.Cell(6, 3).Value = c.TalepTarihi.ToShortDateString();
worksheet.Cell(7, 3).Value = c.TalepTuru;
worksheet.Cell(8, 3).Value = c.ModulAdi;
worksheet.Cell(9, 3).Value = c.EkranRaporAdi;
worksheet.Cell(10, 3).Value = c.VerilenSure;
worksheet.Cell(11, 4).Value …Run Code Online (Sandbox Code Playgroud) c# asp.net visual-studio-2010 nullreferenceexception excelpackage

为什么VS 2012在显示Type变量时将其显示为NullReferenceException value = "Retailer".

我有一个新生儿,我正在努力限制睡眠,所以如果我在这里遗漏了一些明显的东西,我会道歉.已经实例化了LoggedInUser.Employer对象,并且此行在1/2时间内工作正常.但随后它开始破裂.不确定这是否有帮助 - 需要睡觉......
private string _type;
public string Type
{
get { return _type; }
set
{
if (value != null)
{
TypeEnum = (Constants.BusinessType)Enum.Parse(typeof(Constants.BusinessType), value, true);
_type = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我开始怀疑它是否是一个跨线程的问题......

c# .net-4.0 nullreferenceexception visual-studio-debugging visual-studio-2012
我发现了一个奇怪的错误
@{
Layout = null;
}
Run Code Online (Sandbox Code Playgroud)
这是错误:
你调用的对象是空的.
描述:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息.
异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例.
并且堆栈跟踪:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Home_Index_cshtml.Execute() in f:\Web Prog\my work\mcpd\mvc\FilippoPhotography\FP.WebUI\Views\Home\Index.cshtml:4
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177 …Run Code Online (Sandbox Code Playgroud) 为什么设置SelectedValue的ComboBox,以null引起ArgumentNullException?
仅当ComboBox实际上是表单的一部分时才会发生异常.我可以设置SelectedValue各种没有意义的值或类型,但我无法设置它null.
这SelectedValue不是不可能的null.事实上,它的价值是 null在我试图将其设置为时null.
在我的真实代码中,这不会发生在构造函数中,而且我并没有明确地将其设置为null.代码正在使用恰好是的变量null.我可以通过null在尝试设置之前检查变量来修复它SelectedValue.但我不明白的是为什么我不能把它设置为一个null值.
代码编辑:DataSource现在包含ValueMembers值实际的项目null
using System.Collections.Generic;
using System.Windows.Forms;
public class Form1 : Form {
public Form1() {
var comboBox1 = new ComboBox();
Controls.Add(comboBox1);
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.DataSource = new List<Record> {
new Record {Key = "1", Value = "One"},
new Record …Run Code Online (Sandbox Code Playgroud) 只是想确定我没有编写太长时间...但是,这似乎不太可能:
http://i.imgur.com/TBjpNTX.png
我创建var,检查null,如果是,则返回,所以我无法在那时看到它为null :)
Resharper bug?
编辑:
根据Igal Tabachnik的回答,他是对的,我正在使用以下方法扩展:
public static bool IsNullOrEmpty(this string target)
{
return String.IsNullOrEmpty(target);
}
Run Code Online (Sandbox Code Playgroud)
我发现它更容易阅读
if (some_string.IsNullOrEmpty())
// do something here
Run Code Online (Sandbox Code Playgroud)
而不是:
if (string.IsNullOrEmpty(some_string))
// do something here
Run Code Online (Sandbox Code Playgroud)
解决方案:
Igal Tabachnik是对的.唯一缺少的2件是:
c# ×8
asp.net ×2
.net-4.0 ×1
asp.net-mvc ×1
c#-4.0 ×1
c++ ×1
callback ×1
combobox ×1
datasource ×1
datatable ×1
excelpackage ×1
exception ×1
javascript ×1
marshalling ×1
null ×1
object ×1
string ×1
vb.net ×1
winforms ×1