I'm trying to dynamically create a connection string during compile time:
private static string m_ConnectionString
{
get
{
string connectionString = @"Data Source=" + myLibrary.common.GetExeDir() + @"\Database\db.sdf;";
开发者_如何转开发 return connectionString;
}
}
public static string ConnectionString = m_ConnectionString;
I keep running into type initialisation errors. ConnectionString ends up null at runtime. I was trying to avoid having to set the connection string for all applications that user my code library. The location of the database is different for each project that uses the library. I have code that can determine the correction string, but was wanting run it during class initialisation. Is this even possible?
I agree with Oliver's approach to discover the error, but would like to add that you could put this in a static constructor. This would achieve your requirement of "during class initialization".
public static string ConnectionString { get; private set; }
static MyClass()
{
ConnectionString = @"Data Source=" + myLibrary.common.GetExeDir() + @"\Database\db.sdf;";
}
Just set a breakpoint and step into your function and try to find out what is going wrong.
Maybe there will be some exception be thrown which you actually don't see (in some underlying code). To find these cases you should go in Visual Studio to Debug - Exceptions and check all the boxes in the list. Maybe you can find this way, why you get a null instead of a string.
That code is executed at runtime, not compile time. I think you're going down the wrong track.
Another program running as a pre build event could modify the source code of the resources.resx file, prior to compilation. You then get your connection string as a resource string.
Kind of a hack, but not the worst thing I've ever seen. My versions numbers are incremented in a similar way.
精彩评论