Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 18

289
votes
answers
16 views
+10

Auto column width in EPPlus

How to make columns to be auto width when texts in columns are long?

I use this code

 Worksheet.Column(colIndex).AutoFitColumn() 'on all columns'
 Worksheet.cells.AutoFitColumns()
 Worksheet.Column(colIndex).BestFit = True  'on all columns'

None of these methods are working

Is there any ways to make it work?

Note: Some of my texts use Unicode.

沙发
+2120

使用 AutoFitColumns ,但你必須指定單元格,我假設整個工作表:

VB.NET

  Worksheet.Cells (Worksheet.Dimension.Address).AutoFitColumns()  

C#

  Worksheet.Cells [Worksheet.Dimension.Address] .AutoFitColumns();   

請注意,您需要在填寫工作表後調用此方法。

它不起作用。 - Pengan 2013年3月28日10:33

這確實有效... ToString甚至不需要 - Beejee 2013年10月23日11:57

重要的是,您需要在填充工作表後調用此方法,因為如果工作表中沒有數據,Worksheet.Dimension屬性將返回null。 - Landeeyo 2015年1月23日10:22

當我沒有提供任何參數時,AutoFitColumns方法對我不起作用,當我為它添加最小和最大寬度時,它工作得很好。 - Zeeshan Ajmal 2015年4月29日9:53

這絕對是正確的答案 - Pangan應該這樣標記。 - GDB 2015年11月21日14:10

板凳
+360

我已將此代碼與EPPlus的3.1.3.0版本一起使用,它正在運行:

  worksheet.Column(1).AutoFit();   

其中工作表是引用我在代碼中創建的工作表的變量(不是帶有靜態方法的類!)。

顯然你必須填寫完後調用此方法。

整天都在犯錯誤。“這個平台不支持System.Drawing。” - Kursat Turkay 18年3月24日12:34

它對我有用。謝謝傢伙:) - Sadik Ali 7月4日在10:01

地板
+130

我知道這是一個老問題,但我使用下面的代碼,它似乎直接解決了你試圖做的事情。

  using(var xls = new ExcelPackage()) {var ws = xls.Workbook.Worksheets.Add(“Some Name”); // **將列名添加到工作表中!** // **將數據添加到工作表中!** const double minWidth = 0.00; const double maxWidth = 50.00; ws.Cells.AutoFitColumns(minWidth,maxWidth); return pkg.GetAsByteArray(); }  
     
			
        
4楼
+90

我知道有點遲了但我今天遇到了同樣的問題。如果您定義了 worksheet.DefaultColWidth ,則無法使用。我刪除了該行並添加了 Worksheet.cells.AutoFitColumns(); ,現在可以正常工作。

sheet.Cells.AutoFitColumns()更簡單,感謝提示!在ClosedXml中,你做sheet.Columns()。AdjustToContents() - nawfal 16年6月26日在7:03

5楼
+80

只是想指出你可以在不指定範圍的情況下調整單元格,只需確保在格式化所有列之後調用它等:

  worksheet.Cells.AutoFitColumns()  
     
			
        
6楼
+50

它對我來說很好。

嘗試:

  ExcelWorksheet wsSheet1 = ExcelPkg.Workbook.Worksheets.Add(“Sheet1”); wsSheet1.Cells [wsSheet1.Dimension.Address] .AutoFitColumns(); ExcelPkg.SaveAs();  
     
			
        
7楼
+30

您需要計算寬度。庫中沒有自動調整功能可以按預期工作。

Autofitcolumn不適用於包裝文本和帶公式的單元格。

查看 http://epplus.codeplex.com/discussions/218294?ProjectName=epplus 有關如何解決的示例問題。

epplus.codeplex.com/discussions/218294?ProjectName=epplus我找不到任何解決此問題的方法。 - Pengan 2013年3月28日6:22

好了,既然您已經理解了這個問題的答案,請通過預測結果來檢查您的理解:short myShort = 0; int myInt = 0; Console.WriteLine(“{0} {1} {2}”,myShort.Equals(myInt),myInt.Equals(myShort),myInt == myShort); 現在檢查它與現實。你的預測是否正確?如果沒有,你能解釋這個差異嗎? - Eric Lippert 2013年12月17日19:17

@Star,推薦閱讀有關int16 aka short Equals方法的可用重載,請參閱msdn.microsoft.com/en-us/library/vstudio/,然後查看msdn.microsoft.com/en-us/library/ms173105。 ASPX。我不想破壞Eric Lippert的謎題,但是一旦你閱讀了那些頁面就應該很容易理解。 - Sam Skuce 13年12月17日21:41

我以為這是一個java問題; 至少在看到等於'E'之前。 - seteropere 13年12月17日22:46

@seteropere Java實際上是不同的:Java中的自動裝箱會緩存對象,因此((整數)0)==((整數)0)的計算結果為true。 - Jules 2013年12月18日4:36

您也可以嘗試IFormattable x = 0; bool test =(object)x ==(object)x;。當結構已經在框中時,不執行新的裝箱。 - Jeppe Stig Nielsen 2013年12月18日10:16

8楼
+20

不得不使用 worksheet.Column(1).AutoFit(0); AutoFit()沒有做到這一點。

C#語言規範第7.10.6節說:預定義的引用類型相等運算符是:bool operator ==(object x,object y); bool operator!=(對象x,對象y); 運算符返回比較兩個引用的結果是否相等或不相等。不要求使用System.Object.ReferenceEquals方法來確定結果。至@markmnl:不,C#編譯器不內聯,這是抖動有時會發生的事情(但在這種情況下不是)。所以280Z28是正確的,實際上沒有使用ReferenceEquals方法。 - Jeppe Stig Nielsen 2013年12月18日10:39

很酷,很高興知道 - markmnl 13年12月18日12:36

9楼
+10

我使用它並且運行良好。

  Dim objExcel As New ExcelPackage Dim Sheet As ExcelWorksheet = objExcel.Workbook.Worksheets.Add(“SheetName”)Sheet.Cells(“B1: BN“)。AutoFitColumns() 
     
			
        

你能否對你的代碼做一個更全面的解釋? - Shawn 12年5月5日20:39

0
votes
answers
60 views
+10

Marshal.SizeOf()無法計算包含字符串的對象的大小

0

Marshal.SizeOf()將在嘗試計算MyClass類型的對象的長度時引發異常。Marshal.SizeOf()無法計算包含字符串的對象的大小

這裏是類:

<StructLayout(LayoutKind.Sequential, Pack:=1)> 
Public Class MyClass 

    Public ReadOnly UniqueId As Long 

    <MarshalAs(UnmanagedType.AnsiBStr, SizeConst:=60, SizeParamIndex:=0)> 
    Public ReadOnly Name As String 

End Class 

該代碼將失敗:

Dim MyObject = New MyClass() 
Dim size = Marshal.SizeOf(MyObject) 'will throw exception here. Why? 

它會拋出異常「任何有意義的大小或偏移量可以計算」

我怎樣才能取而代之的是MyObject的長度?

+0

什麼平臺你正在使用 – Adrian

+0

這個問題似乎與'AnsiBStr'。 'BStr' /'LPStr' /'LPWStr'似乎很好https://stackoverflow.com/questions/64714??21/marshal-c-char-in-c-sharp – Slai

+0

我正在編譯到x64 Windows中的AnyCPU。 –

沙发
0
0

我相信UnmanagedType.AnsiBStr只能用於方法簽名的參數(傳遞值)。

對BSTR的引用是指向長度前綴字符數組的指針。因此,它將是一個.Net Intptr,其大小爲4或8個字節,具體取決於進程位(x32或x64)。如果您需要ANSI字符,可以定義爲StructLayout聲明的一部分並標記字符串作爲UnmanagedType.BStr

<StructLayout(LayoutKind.Sequential, Pack:=1, CharSet:=CharSet.Ansi)> 
Public Class [MyClass] 
    Public ReadOnly UniqueId As Long 
    <MarshalAs(UnmanagedType.BStr)> 
    Public ReadOnly Name As String 
End Class 

推薦閱讀:

板凳
0
-1

即時通訊設法幫助。馬歇爾用於值類型例如:結構類別引用類型這是不需要計算內部未使用的對象。你需要使用ex:struct來完成它的工作。我給我的代碼的例子,但對不起,我寫在C#

class Program 
{ 
    static void Main(string[] args) 
    { 
     TestingData p = new TestingData(); 
     Console.WriteLine("Number of bytes : {0}", Marshal.SizeOf(p)); 
    } 
} 

public struct TestingData 
{ 
    public string a; 
} 

希望它的幫助。欲瞭解更多信息,你可以去這裏Marshal Documentation

0
votes
answers
35 views
+10

試圖在2個文本框的標籤上顯示「hh:mm」

0

我有兩個TextBox元素:textbox1小時和textbox2分鐘。我已經嘗試了很多代碼,但他們不適合我。我總是得到:試圖在2個文本框的標籤上顯示「hh:mm」

從字符串「1」到類型「日期」的轉換無效。

我想從兩個文本框(textbox1textbox2)的標籤上顯示的時間(格式爲hh:mm)。

+3

您好,歡迎堆棧溢出。在這裏正確提出問題真的很重要。看看[問]和[mcve]。謝謝 –

+2

大寫字母通常被認爲是在網上喊 - 請不要這樣做。無論如何,你嘗試了什麼代碼?聽起來像也許你試圖把東西變成日期。但是,如果你只是想重新顯示它,那麼只是保持一個字符串有什麼問題?目前尚不清楚。 – ADyson

沙发
0
1

我?思?你想從文本框的值解析成一個DateTime,和T文檔母雞顯示在一個標籤?如果是這樣,嘗試這樣的事情:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    Dim dt As DateTime 
    If DateTime.TryParse(TextBox1.Text & ":" & TextBox2.Text, dt) Then 
     Label1.Text = dt.ToString 
    End If 
End Sub 

如果你想只顯示時間部分,則:

Label1.Text = dt.ToString("h:mm tt") 
+0

非常感謝你!這是我第一次問這裏,請原諒我問的方式。 – KLANG

板凳
0
0

的,U沒有提及ü嘗試了任何代碼首先far.However的解決辦法是:

textbox1.text=DateTime.Now.ToString("HH") 
textbox2.text=DateTime.Now.ToString("mm") 

UR越來越Cannot convert string to date例外,這可以通過使用ToString。在碼固定, HH代表Hoursmm代表minutes 爲了更好地理解,閱讀DateTime.Now

+0

編輯我的答案球員,我感謝您的意見 –

+0

非常感謝您瞭解我的無意義的問題。讚賞。 – KLANG

+0

將答案標記爲答案,如果它有幫助@klang –

0
votes
answers
24 views
+10

VB.NET在更多的項目中使用相同的子類

0

很少我的控制分類爲獲得更好的我的程序總體結果。這些子類繼承自原始的NET控件。我在VB.NET ide的工具箱下有它。假設我用它在PROJECT1窗體設計器的地方它在形式上像這樣:VB.NET在更多的項目中使用相同的子類

Me.btn_OK = New Project1.xButton() 

之後,我創建一個新項目:Project2中添加這些子類像文件「爲紐帶」到這些新的項目。爲了讓它起作用,我刪除了「Project1」。從它的名字。當我編譯出現該項目新definiton:

Me.btn_OK = New Project2.xButton() 

這也適用不錯,但沒有更多的PROJECT1,我不得不刪除「Project2的。」再次得到它的工作。

這裏是我的東西可以做,VB.NET可能會留下這樣的分配:

Me.btn_OK = New xButton() 

什麼會讓我使用相同的子類文件中兩個(或更多)的項目? 歡迎任何其他相關建議。

+0

您可以將它們存儲在某種庫文件夾,然後在另一個項目中使用它們,添加使用'加爲Link'的項目。不知道這是否是你要求的 – Plutonix

+0

我這樣做,但每個項目都將他的名字添加到這些控件,使其他項目無法使用, –

+0

不確定你的意思。如果您將控件(不是項目)的類文件作爲鏈接導入,則必須導入該名稱空間。改造可能是一種痛苦,但如果設計成從一開始就以這種方式使用,那麼就沒有問題,並且它們完全(重新)可用。 – Plutonix

沙发
0
0

您需要創建一個新項目,選擇Visual Basic類庫。將您的課程添加到此項目中,然後在Project1和Project2中引用新項目。

Microsoft Tutorial

+0

這樣我會產生一個dll文件什麼是不想要的。還有一件事需要擔心(調試/發佈)和部署。我希望其他一些更多的VB基本方式存在。 –

+0

@WineToo,_在工作中有一件事需要擔心 - 「一件大事」vs「多件小事」。 – Fabio

0
votes
answers
21 views
+10

BackgroundWorker引發的事件未在預期線程上執行

1

winforms對話框正在使用BackgroundWorker執行一些異步操作並取得重大成功。有時,由後臺工作人員運行的異步進程需要將事件引發到用戶響應的WinForms應用程序(詢問用戶是否希望取消的消息),其響應在事件的CancelEventArgs類型中捕獲。作爲一個線程的實現,我會期待工人的RaiseEvent被觸發,然後工作者會繼續,因此需要我暫停工作,直到收到響應。但是,工作人員會等待由加註事件執行的代碼完成。BackgroundWorker引發的事件未在預期線程上執行

看起來好像是我通過事件調用調用的方法實際上是由後臺工作人員使用的工作線程,我很驚訝,因爲我期望在主線程正在運行的主線程上看到它。另外令人驚訝的是,沒有交叉線程異常拋出。

有人能解釋爲什麼這不是我所期望的嗎?

沙发
0
2

BackgroundWorker的將提高其ProgressChanged事件,並在UI線程上RunWorkerCompleted事件(更準確地說,它會把它們張貼到使用當前建立的SynchronizationContext線程)。

但它不會簡單地讓你提高任意UI線程上的事件。爲此,您應該訪問SynchronizationContext.Current並使用Post方法。

+0

謝謝Josh,看起來不錯,明天我會看看。我仍然感到驚訝的是,當我從該事件調用Windows.Forms.Messagebox.Show時,因爲它仍然位於後臺線程中,所以未引發交叉線程異常。 – Topdown 2010-03-22 11:23:24

+0

有沒有這樣的事情作爲「UI線程」,只是碰巧是一個線程,你只能從UI運行。任何線程都可以調用像MessageBox之類的UI東西,或者創建並顯示WinForms。同樣,您的工作線程並不真正知道它正在運行異步,因此事件被引發,就像它正在正常運行一樣。 – 2010-03-22 13:00:31

+0

從技術上來說,Chris是正確的,但是從一個當前沒有消息循環的線程調用MessageBox.Show會導致創建一個(否則MessageBox將無法工作),所以我同意如果有非法的檢查會很好跨線程訪問Windows窗體控件的工作方式。 – Josh 2010-03-22 14:19:44

0
votes
answers
28 views
+10

如何讓我的控制檯窗口打開? VB

-1

我想讓我的控制檯窗口在Visual Basic中打開。用我的代碼,我只能要求一行,然後窗口關閉。這裏是我的代碼:如何讓我的控制檯窗口打開? VB

Module Module1 

Sub Main() 

    If (Console.ReadLine = "e") Then 
     Console.WriteLine("Test") 
    End If 

    Console.ReadKey() 

End Sub 

End Module 

所以當我運行這段代碼時,我可以輸入「e」按回車。單詞出現「測試」,然後控制檯在按下一個鍵後關閉。但是我想讓它開放直到我寫一個特殊的單詞。

沙发
0
0

這是一個愚蠢的例子:

Sub Main() 
    Dim password As String = "007" 

    Dim response As String 
    Do 
     Console.Write("Password: ") 
     response = Console.ReadLine 
     If response <> password Then 
      Console.WriteLine("Incorrect Password!") 
     End If 
    Loop While response <> password 

    Console.WriteLine("Welcome James Bond!") 
    Console.Write("Press [Enter] to proceed...") 
    Console.ReadLine() 
End Sub 
+0

謝謝您的回答。它的作品如何我想要它! – notraffic

0
votes
answers
30 views
+10

所有選定的DataGridview行顯示到另一個窗體的文本框vb.net

-1

我試圖顯示我的DataGridView的所有選定的行到一個文本框只有多行。但是,我嘗試過的所有代碼都不起作用。所有選定的DataGridview行顯示到另一個窗體的文本框vb.net

這裏是我選擇我的DataGridView

Dim form2 As New Form2 
Form2.txtreceipt.Text = DataGridView1.SelectedRows.ToString 
Form2.Show() 
沙发
0
0

SelectedRows返回的DataGridViewRow的集合,而不是單個給定的DataGridViewRow的特定細胞中的所有行之後,我嘗試了樣品。據推測,您的DataGridView綁定到BindingSource,如果是這種情況,那麼您可以將BindingSource傳遞給Form2作爲New構造函數中的參數,並在那裏設置控件(s)數據綁定。

因此,例如,你的窗體2將包含以下代碼:

Sub New(ByVal source As BindingSource) 
    txtreceipt.DataBindings.Add(New Binding("Text", source, "Receipt", True)) 
End Sub 

然後每當你想顯示你會打電話的形式:

Using frm2 As Form2 = New Form2(BindingSource1) 
    frm.ShowDialog() 
End Using 
13
votes
answers
28 views
+10

What is a NullReferenceException, and how do I fix it?

I have some code and when it executes, it throws a NullReferenceException, saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do to fix this error?

沙发
+80

Interestingly, none of the answers on this page mention the two edge cases, hope no one minds if I add them:

Edge case #1: concurrent access to a Dictionary

Generic dictionaries in .NET are not thread-safe and they sometimes might throw a NullReference or even (more frequent) a KeyNotFoundException when you try to access a key from two concurrent threads. The exception is quite misleading in this case.

Edge case #2: unsafe code

If a NullReferenceException is thrown by unsafe code, you might look at your pointer variables, and check them for IntPtr.Zero or something. Which is the same thing ("null pointer exception"), but in unsafe code, variables are often cast to value-types/arrays, etc., and you bang your head against the wall, wondering how a value-type can throw this exception.

(Another reason for non-using unsafe code unless you need it, by the way)

板凳
+30

NullReferenceException or Object reference not set to an instance of an object occurs when an object of the class you are trying to use is not instantiated. For example:

Assume that you have a class named Student.

public class Student
{
    private string FirstName;
    private string LastName;
    public string GetFullName()
    {
        return FirstName + LastName;
    }
}

Now, consider another class where you are trying to retrieve the student's full name.

public class StudentInfo
{      
    public string GetStudentName()
    {
        Student s;
        string fullname = s.GetFullName();
        return fullname;
    }        
}

As seen in the above code, the statement Student s - only declares the variable of type Student, note that the Student class is not instantiated at this point. Hence, when the statement s.GetFullName() gets executed, it will throw the NullReferenceException.

地板
+20

Well, in simple terms:

You are trying to access an object that isn't created or currently not in memory.

So how to tackle this:

  1. Debug and let the debugger break... It will directly take you to the variable that is broken... Now your task is to simply fix this.. Using the new keyword in the appropriate place.

  2. If it is caused on some database commands because the object isn't present then all you need to do is do a null check and handle it:

    if (i == null) {
        // Handle this
    }
    
  3. The hardest one .. if the GC collected the object already... This generally occurs if you are trying to find an object using strings... That is, finding it by name of the object then it may happen that the GC might already cleaned it up... This is hard to find and will become quite a problem... A better way to tackle this is do null checks wherever necessary during the development process. This will save you a lot of time.

By finding by name I mean some framework allow you to FIndObjects using strings and the code might look like this: FindObject("ObjectName");

4楼
0

If we consider common scenarios where this exception can be thrown, accessing properties withing object at the top.

Ex:

string postalcode=Customer.Address.PostalCode; 
//if customer or address is null , this will through exeption

in here , if address is null , then you will get NullReferenceException.

So, as a practice we should always use null check, before accessing properties in such objects (specially in generic)

string postalcode=Customer?.Address?.PostalCode;
//if customer or address is null , this will return null, without through a exception
5楼
0

Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

  1. Add a RigidBody to your object with AddComponent > Physics > Rigidbody
    Then go into your script and type rb = GetComponent<Rigidbody>();
    This line of code works best under your Start() or Awake() functions.
  2. You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent<RigidBody>();

Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).
Enjoy and have fun making games!

6楼
-10

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.

7楼
-10

To use methods and member of an object you first have to create that object. If you didn't create it (variable that should hold the object is not initialized), but you try to use it's methods or variables you'll get that error.

Sometime you may just forgot to do initialization.

Edited: new can't return null, but fire's exception when failed. Long time ago it was the case in some languages, but not any more. Thanks @John Saunders for pointing that out.

8楼
-20

This is basically is a Null reference exception. As Microsoft states-

A NullReferenceException exception is thrown when you try to access a member of a type whose value is null.

What does that mean?

That means if any member which doesn’t hold any value and we are making that member to perform certain task then the system will undoubtedly toss a message and say-

“Hey wait, that member has no values so it can’t perform the task which you are handing it over.”

The exception itself says that something is being referred but whose value is not being set. So this denotes that it only occurs while using reference types as Value types are non-nullable.

NullReferenceException won't occur if we are using Value type members.

class Program
{
    static void Main(string[] args)
    {
        string str = null;
        Console.WriteLine(str.Length);
        Console.ReadLine();
    }
}

The above code shows simple string which is assigned with a null value.

Now, when I try to print the length of the string str, I do get An unhandled exception of type ‘System.NullReferenceException’ occurred message because member str is pointing to null and there can’t be any length of null.

NullReferenceException’ also occurs when we forget to instantiate a reference type.

Suppose I have a class and member method in it. I have not instantiated my class but only named my class. Now if I try to use the method, the compiler will throw an error or issue a warning (depending on the compiler).

class Program
{
    static void Main(string[] args)
    {
        MyClass1 obj;
        obj.foo();  //Use of unassigned local variable 'obj'
    }
}

public class MyClass1
{
    internal void foo()
    {
        Console.WriteLine("hello from foo");

    }
}

Compiler for the above code raises an error that variable obj is unassigned which signifies that our variable has null values or nothing. Compiler for the above code raises an error that variable obj is unassigned which signifies that our variable has null values or nothing.

Why it occurs?

  • NullReferenceException arises due to our fault for not checking the object’s value. We often leave the object values unchecked in the code development.

  • It also arises when we forget to instantiate our objects. Using methods, properties, collections etc. which can return or set null values can also be the cause of this exception.

How can it be avoided?

There are various ways and methods to avoid this renowned exception:

  1. Explicit Checking: We should adhere to the tradition of checking the objects, properties, methods, arrays, and collections whether they are null. This can be simply implemented using conditional statements like if-else if-else etc.

  2. Exception handling: One of the important ways of managing this exception. Using simple try-catch-finally blocks we can control this exception and also maintain a log of it. This can be very useful when your application is on production stage.

  3. Null operators: Null Coalescing operator and null conditional operators can also be used in handy while setting values to objects, variables, properties and fields.

  4. Debugger: For developers, we have the big weapon of Debugging with us. If have we face NullReferenceException during the development face we can use the debugger to get to the source of the exception.

  5. In-built method: System methods such as GetValueOrDefault(),IsNullOrWhiteSpace() and IsNullorEmpty() checks for nulls and assign the default value if there is a null value.

There are many good answers already here. You can also check more detailed description with examples on my blog.

Hope this helps too!

9楼
-50

There is a scenario that can happen that is Class related. The question ended up getting closed prior to my stating the resolution: https://stackoverflow.com/questions/43348009/unable-to-instantiate-class

Beware of classes not instantiating: If any part of your constructor in a class throws a null reference exception the class does not instantiate. In my case it was trying to get a connection string from the web.config that that did not exist.

I instantiated a class:

ClassName myClass = new ClassName();
myClass.RunSomeMethod();

Inside the class itself was a call to get a connection string from the web.config. This part of the constructor threw an null value exception so myClass was null.

If you ever have a situation where a class in not instantiating, try making sure that no part of the class constructor Is throwing a null value exception. F-11 and step through the class and make sure there are no nulls.

0
votes
answers
19 views
+10

什麼interace爲的System.Array類的運行時實現在.net中是什麼意思?

0

documentation什麼interace爲的System.Array類的運行時實現在.net中是什麼意思?

[...] Array類實現了System.Collections.Generic.IList<T>System.Collections.Generic.ICollection<T>System.Collections.Generic.IEnumerable<T>通用接口。 實現在運行時提供給數組,因此對文檔構建工具不可見。

這是提供給C#開發人員。我的意思是我可以提供運行時實現到任何類的接口嗎?

+0

文檔只能拿你這一步,如果你想進一步挖掘,閱讀源代碼,https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/ Array.cs –

+1

https://stackoverflow.com/q/11163297/17034 –

+0

感謝@HansPassant。正是我需要的。 –

沙发
0
2

是,數組是特殊的,準確地表現爲鏈接的文件說。

不,你不能隨心所欲(甚至特定的)接口的類在運行時,除非你正在創建自己的實現CLR的補充。

注意,有很多方法來模擬接口加入喜歡的擴展方法或代理類包裝的對象,但有添加接口類動態沒有真正的辦法的行爲。

+0

感謝您的解釋。所以,這個動態接口實現是CLR內置的邏輯,只適用於數組類型。 –

1361
votes
answers
22 views
+10

How to enable assembly bind failure logging (Fusion) in .NET

How do I enable assembly bind failure logging (Fusion) in .NET?

沙发
+8040

Add the following values to

HKEY_LOCAL_MACHINESOFTWAREMicrosoftFusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
DWORD EnableLog set value to 1
String LogPath set value to folder for logs (e.g. C:FusionLog)

Make sure you include the backslash after the folder name and that the Folder exists.

You need to restart the program that you're running to force it to read those registry settings.

BTW, don't forget to turn off fusion logging off when not needed.

加里的解決方案對我有用,雖然我也不得不關注重置IIS。注意我在乾淨的環境中配置了這個,我不想安裝SDK等。 - 2010年7月30日凌晨2點21分

據一些人報導,註冊表更改不會馬上進行。您是否嘗試過啟用Fusion登錄然後重新啟動? - Gary Kindel 2010年12月6日20:18

您需要重新啟動它正在運行的任何程序才能讀取這些註冊表設置 - Orion Edwards 2011年3月28日22:29

Fusion Log Viewer為您完成所有這些工作。轉到開始 - >程序 - > Visual Studio xxxx> Visual Studio工具> Visual Studio命令提示符(以管理員身份運行),然後鍵入“fuslogvw”。在“設置”中,調整日誌記錄。 - r3mark 2013年6月4日3:09

為了方便地打開/關閉日誌記錄,我創建了.reg文件,這些文件基於Gary Kindel的答案:啟用和禁用。 - Igor Kustov 2013年11月19日7:16

板凳
+2480

I usually use the Fusion Log Viewer (Fuslogvw.exe from a Visual Studio command prompt or Fusion Log Viewer from the start menu) - my standard setup is:

  • Open Fusion Log Viewer as administrator
  • Click settings
  • Check the Enable custom log path checkbox
  • Enter the location you want logs to get written to, for example, c:FusionLogs (Important: make sure that you have actually created this folder in the file system.)
  • Make sure that the right level of logging is on (I sometimes just select Log all binds to disk just to make sure things are working right)
  • Click OK
  • Set the log location option to Custom

Remember to turn of logging off once you're done!

(I just posted this on a similar question - I think it's relevant here too.)

請注意,如果您自己從本機應用程序託管運行時,由於某種原因,您將需要使用自定義日誌路徑,否則您將無法記錄任何內容。 - jpierson 12年4月4日在3:34

至少在我的情況下,我實際上不必設置自定義日誌路徑。我所要做的只是打開登錄,例如,在設置對話框中“記錄所有綁定到磁盤”。 - 約什在2014年7月31日20:11

在我的情況下需要以管理員身份運行,否則所有選項都被禁用。 - vezenkov 2016年8月12日12:32

注意:創建文件夾為Admin! - Tabrock 2017年5月10日21:07

確保您不僅以管理員身份運行fuslogvw,而且還從正確的Windows SDK路徑運行引發異常的Visual Studio項目。檢查其csproj並在其中搜索SDK(我的sdk節點名為TargetFrameworkSDKToolsDirectory)。使用不匹配的fuslogvw版本似乎沒有捕獲異常(這是有道理的...) - Veverke 17年6月12日在14:28

地板
+1860

If you have the Windows SDK installed on your machine, you'll find the "Fusion Log Viewer" under Microsoft SDKTools (just type "Fusion" in the start menu on Vista or Windows 7/8). Launch it, click the Settings button, and select "Log bind failure" or "Log all binds".

If these buttons are disabled, go back to the start menu, right-click the Log Viewer, and select "Run as Administrator".

這些按鈕對我來說是禁用的 - 為什麼? - 蒂姆·洛弗爾 - 史密斯2010年8月24日22:11

@Tim,之前沒見過 - 可能與Admin權限有關嗎?畢竟是HKEY_LOCAL_MACHINE正在被修改。 - 塞繆爾杰克2010年9月24日15:35

“設置,日誌綁定失敗”足以找到我的問題。 - pauloya 2011年8月16日中午12點

確保該文件夾允許寫訪問。UAC和c:日誌與融合日誌不一致 - 愛德華王爾德2013年2月20日9:27

就像注意一樣,如果按鈕被禁用,請使用管理員權限重新運行Fusion日誌查看器。 - Bruno Lopes 2013年3月7日19:33

4楼
+840

Set the following registry value:

[HKEY_LOCAL_MACHINESOFTWAREMicrosoftFusion!EnableLog] (DWORD) to 1

To disable, set to 0 or delete the value.

[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESOFTWAREMicrosoftFusion]
"EnableLog"=dword:00000001

Then run the file from windows explorer and ignore the warning about possible damage.

並不是說條目可能不存在 - 你必須創建它。至少,我在今天早上崩潰前即將回答這個問題時做了:) - Jon Skeet 08年11月1日15:54

什麼了!意思?關鍵或價值?那麼64位系統呢? - 布魯諾馬丁內斯2009年7月14日15:21

實際上,這確實有效......你只需要運行iisreset後來使其工作。 - Nick DeMayo 2010年6月22日13:02

@Norman:因為此特定設置用於使Asp.Net錯誤在錯誤頁面中顯示程序集綁定錯誤消息,而不是將日誌保存到文件。@OP:+1。編輯包含.reg文件。的!格式是我從未見過的格式,除了發送給我在此頁面尋找答案的錯誤消息。 - 布萊恩2011年2月8日21:53

您不需要重置IIS - 只需要重置相關的應用程序池。或者至少那是我需要做的。 - Kenny Evitt 2015年1月23日16:54

5楼
+190

The Fusion Log Settings Viewer changer script is bar none the best way to do this.

In ASP.NET, it has been tricky at times to get this to work correctly. This script works great and was listed on Scott Hanselman's Power Tool list as well. I've personally used it for years and its never let me down.

ps確認您在運行後禁用它或此文件夾可能會變得非常大 - Adam Tuliper - MSFT 12年9月19日在0:32

這就是為什麼我使用ETW,只記錄我真正需要的數據,而不是一直在醜陋的大日誌文件中。 - magicandre1981 2015年4月3日6:58

6楼
+120

Instead of using a ugly log file, you can also activate Fusion log via ETW/xperf by turning on the DotnetRuntime Private provider (Microsoft-Windows-DotNETRuntimePrivate) with GUID 763FD754-7086-4DFE-95EB-C01A46FAF4CA and the FusionKeyword keyword (0x4) on.

@echo off
echo Press a key when ready to start...
pause
echo .
echo ...Capturing...
echo .

"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -on PROC_THREAD+LOADER+PROFILE -stackwalk Profile -buffersize 1024 -MaxFile 2048 -FileMode Circular -f Kernel.etl
"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -start ClrSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+763FD754-7086-4DFE-95EB-C01A46FAF4CA:0x4:0x5 -f clr.etl -buffersize 1024

echo Press a key when you want to stop...
pause
pause
echo .
echo ...Stopping...
echo .

"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -start ClrRundownSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+Microsoft-Windows-DotNETRuntimeRundown:0x118:0x5:'stack' -f clr_DCend.etl -buffersize 1024 

timeout /t 15

set XPERF_CreateNGenPdbs=1

"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -stop ClrSession ClrRundownSession 
"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -stop
"C:Program Files (x86)Windows Kits8.1Windows Performance Toolkitxperf.exe" -merge kernel.etl clr.etl clr_DCend.etl Result.etl -compress
del kernel.etl
del clr.etl
del clr_DCend.etl

When you now open the ETL file in PerfView and look under the Events table, you can find the Fusion data:

Fusion events in PerfView

@YuriBondarchuk根據需要激活它,你在ETL(其他進程,fileversion數據)中有更多數據,這樣你就可以給其他用戶提供文件了,與普通的融合日誌相比,他們可以獲得更多信息 - magicandre1981 Sep 17' 15點4分04分

7楼
+30

Just a tiny bit of info that might help others; if you do something along the lines of searching all assemblies in some directory for classes that inherit/implement classes/interfaces, then make sure you clean out stale assemblies if you get this error pertaining to one of your own assemblies.

The scenario would be something like:

  1. Assembly A loads all assemblies in some folder
  2. Assembly B in this folder is stale, but references assembly C
  3. Assembly C exists, but namespaces, class names or some other detail might have changed in the time that has passed since assembly B became stale (in my case a namespace was changed through a refactoring process)

In short: A ---loads--> B (stale) ---references---> C

If this happens, the only telltale sign is the namespace and classname in the error message. Examine it closely. If you can't find it anywhere in your solution, you are likely trying to load a stale assembly.

8楼
+20

If you already have logging enabled and you still get this error on Windows 7 64 bit, try this in IIS 7.5:

  1. Create a new application pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new pool

9楼
+20

Since my tweet about Fusion++ got retweetet from Scott Hanselman himself, I think I am confident enough to tell you about it.

I wrote an assembly binding log viewer named Fusion++ and put it on GitHub.

I hope you and some of the visitors in here can save some worthy lifetime minutes with it.

Fusion++

親愛的先生,你是上帝! - Sylvain Girard Jun 3於10:14

10楼
+10

Just in case you're wondering about the location of FusionLog.exe - You know you have it, but you cannot find it? I was looking for FUSLOVW in last few years over and over again. After move to .NET 4.5 number of version of FUSION LOG has exploded. Her are places where it can be found on your disk, depending on software which you have installed:

C:Program Files (x86)Microsoft SDKsWindowsv8.0AinNETFX 4.0 Toolsx64

C:Program Files (x86)Microsoft SDKsWindowsv7.0ABinx64

C:Program Files (x86)Microsoft SDKsWindowsv8.1AinNETFX 4.5.1 Toolsx64

C:Program Files (x86)Microsoft SDKsWindowsv8.0AinNETFX 4.0 Tools

C:Program Files (x86)Microsoft SDKsWindowsv8.1AinNETFX 4.5.1 Tools

C:Program Files (x86)Microsoft SDKsWindowsv7.0ABin

發布的列表是針對.net 1.1這裡是3.5 msdn.microsoft.com/en-us/library/system.attribute.aspx的列表(你必須向下滾動一點) - kay.one 09年6月30日在6: 56

更新了問題中的鏈接。現在它是完整的3.5 - R. Martinho Fernandes 09年11月8日13:17

實際上,鏈接到最新,而不是3.5具體。 - Brian Ortiz 2010年6月27日17:29

現在,如果只有列表不僅僅是一個鏈接列表,而是名稱和描述。那好吧。@BrianOrtiz是對的。該列表的版本為4.5。 - 發光於2014年9月10日12:49

您只需將目標框架更改為“其他版本”的頂部。 - Novaterata 2015年2月6日19:01

11楼
0

In my case helped type disk name in lower case

Wrong - C:someFolder

Correct - c:someFolder

這和#if DEBUG一樣嗎? - Neil N 09年8月10日20:11

有點,#if DEBUG意味著調用者也不必調用它,而Conditioinal離開調用但是使它成為一個在JIT被淘汰的NOP。 - Rangoric 2011年3月14日20:10

此外,您通常會在調用周圍使用#if DEBUG,而在方法周圍使用[有條件]。因此,如果你調用100次調試方法,關閉它只需要一次代碼更改,而不是100次。 - Steve Cooper 2011年3月15日11:46

Rangoric的評論是巧妙的錯誤(至少對於C#而言):該方法未被修改; 呼叫站點本身被省略。這有一些含義:不評估參數,並且在編譯器的輸出中包含未修改的條件方法。您可以使用反射驗證這一點。msdn.microsoft.com/en-us/library/aa664622.aspx blogs.msdn.com/b/jmstall/archive/2007/10/15/... - Mark Sowul 12年2月2日20:06

12楼
0

For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:

reg add "HKLMSoftwareMicrosoftFusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLMSoftwareMicrosoftFusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLMSoftwareMicrosoftFusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLMSoftwareMicrosoftFusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLMSoftwareMicrosoftFusion" /v LogPath /t REG_SZ /d C:FusionLog

if not exist "C:FusionLog" mkdir C:FusionLog

不相信沒有人指出描述,直到你..它對我來說最有用的與枚舉.. - nawfal 6年9月9日在8:05