关于SqlException 异常的创建问题。
我的问题是怎样实例化一个SqlException类异常哪?查看MSDN后发现 System.Data.SqlClient.SqlException.CreateExceptioin是用来实例化SqlException的,但是它被标注为internal。所以不在通过正常手段调用它。
请问谁有好为法,不吝赐教。 --------------------编程问答-------------------- try catch
或者
throw new Exception(""); --------------------编程问答-------------------- 貌似不让吧?为什么非要实例化一个这样的类呢?
你可以自己定义一个异常类型来实现的. --------------------编程问答-------------------- 数十天之前发的贴子, 自己找到答案了, 自己回答。
//http://blogs.msdn.com/b/rido/archive/2006/11/26/mocking-sqlexception.aspx
/*
Mocking SQLException
Rido
26 Nov 2006 8:30 AM
I'm working on a presentation about Testing, and one of the technics I would like to show is MockObjects.
One of the mock objects I want to create is a DataAccess Layer, and this one should throw SqlExceptions, however the SqlException class is sealed and has no public constructor.
I found a comment about it here: http://www.taylor.se/blog/2006/06/09/mocking-sqlexception/
But the implementation does not work with .Net2, so I have to refactor the code to create a SqlExceptionCreator, and here it is:
*/
using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Runtime.Serialization;
public class SqlExceptionCreator
{
public static SqlException CreateSqlException(string errorMessage, int errorNumber)
{
SqlErrorCollection collection = GetErrorCollection();
SqlError error = GetError(errorNumber, errorMessage);
MethodInfo addMethod = collection.GetType().
GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance);
addMethod.Invoke(collection, new object[] { error });
Type[] types = new Type[] { typeof(string), typeof(SqlErrorCollection) };
object[] parameters = new object[] { errorMessage, collection };
ConstructorInfo constructor = typeof(SqlException).
GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
SqlException exception = (SqlException)constructor.Invoke(parameters);
return exception;
}
private static SqlError GetError(int errorCode, string message)
{
object[] parameters = new object[] {
errorCode, (byte)0, (byte)10, "server", message, "procedure", 0 };
Type[] types = new Type[] {
typeof(int), typeof(byte), typeof(byte), typeof(string), typeof(string),
typeof(string), typeof(int) };
ConstructorInfo constructor = typeof(SqlError).
GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
SqlError error = (SqlError)constructor.Invoke(parameters);
return error;
}
private static SqlErrorCollection GetErrorCollection()
{
ConstructorInfo constructor = typeof(SqlErrorCollection).
GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
SqlErrorCollection collection = (SqlErrorCollection)constructor.Invoke(new object[] { });
return collection;
}
}
补充:.NET技术 , .NET Framework