যদি আপনি .NET 4.0 বা তদূর্ধ্ব ব্যবহার করছেন এবং আপনি এমন একটি প্রোগ্রামিক সংস্করণ চান যা কোডের বাইরে সংজ্ঞায়িত নিয়মের কোডিকেশন নয় তবে আপনি একটি তৈরি করতে Expression, সংকলন করতে এবং এটিকে অন-ফ্লাইয়ে চালাতে পারেন।
নিম্নলিখিত এক্সটেনশনটি পদ্ধতি গ্রহণ করা হবে Typeএবং থেকে প্রত্যাগত মান পেতে default(T)মাধ্যমে Defaultপদ্ধতি উপর Expressionশ্রেণী:
public static T GetDefaultValue<T>()
{
// We want an Func<T> which returns the default.
// Create that expression here.
Expression<Func<T>> e = Expression.Lambda<Func<T>>(
// The default value, always get what the *code* tells us.
Expression.Default(typeof(T))
);
// Compile and return the value.
return e.Compile()();
}
public static object GetDefaultValue(this Type type)
{
// Validate parameters.
if (type == null) throw new ArgumentNullException("type");
// We want an Func<object> which returns the default.
// Create that expression here.
Expression<Func<object>> e = Expression.Lambda<Func<object>>(
// Have to convert to object.
Expression.Convert(
// The default value, always get what the *code* tells us.
Expression.Default(type), typeof(object)
)
);
// Compile and return the value.
return e.Compile()();
}
উপরের ভিত্তিতে উপরের মানটিও আপনাকে ক্যাশে করা উচিত Type, তবে সচেতন হন যদি আপনি এটিকে প্রচুর সংখ্যক Typeদৃষ্টান্তের জন্য কল করছেন , এবং এটি ক্রমাগত ব্যবহার না করেন, ক্যাশে গ্রাহিত মেমরিটি উপকারের চেয়ে বেশি হতে পারে।