c# - .Net Set Class Constant to it's Namespace at compile time -
is there nice way set constant of classes namespace?
namespace acmecompany.acmeapp.services { public class myservice { private const string whatwedo = "acmecompany.acmeapp.services"; private const string wouldbenice = typeof(myservice).namespace; ... } }
so if class if moved namespace don't need worry these constants.
more info constant used logging - passed log method. legacy code wont changing in short term. aware of runtime ways information such this question
we're using .net 4 upgrading .net 4.5.
you're not going set constant variable non-constant value. understandable, isn't it?
btw, c# has readonly
keyword, turn class field work constant once object construction time ends. can or can't static:
public class myservice { static myservice() { wouldbenice = typeof(myservice).namespace; } private static readonly string wouldbenice; }
or...
public class myservice { private static readonly string wouldbenice = typeof(myservice).namespace; }
also, can achieve same behavior using read-only properties:
// prior c# 6... public class myservice { private static string wouldbenice { { return typeof(myservice).namespace; } } } // using c# 6... public class myservice { private static string wouldbenice => typeof(myservice).namespace; } // using c# 6... public class myservice { // can better, because sets namespace // auto-generated backing class field created during compile-time private static string wouldbenice { get; } = typeof(myservice).namespace; }
Comments
Post a Comment