?? program.cs
字號:
?using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
namespace AutomaticPropertiesDefaultValues
{
class Program
{
static void Main(string[] args)
{
TestObject to = new TestObject();
Console.WriteLine(to.DefaultInt);
Console.WriteLine(to.DefaultDouble);
Console.WriteLine(to.DefaultBool);
Console.WriteLine(to.DefaultEnum);
Console.WriteLine(to.DefaultString ?? "<null>");
Console.WriteLine(to.StringWithoutDefault ?? "<null>");
Console.WriteLine(to.ValueOfPrivateProperty ?? "<null>");
Console.WriteLine();
Console.WriteLine();
TestObjectInherited toi = new TestObjectInherited();
Console.WriteLine(toi.DefaultInt);
Console.WriteLine(toi.DefaultDouble);
Console.WriteLine(toi.DefaultBool);
Console.WriteLine(toi.DefaultEnum);
Console.WriteLine(toi.DefaultString ?? "<null>");
Console.WriteLine(toi.StringWithoutDefault ?? "<null>");
Console.WriteLine(toi.ValueOfPrivateProperty ?? "<null>");
Console.WriteLine(toi.InheritedDefaultValue ?? "<null>");
Console.WriteLine(TestObjectInherited.StaticProperty ?? "<null>");
Console.ReadLine();
}
}
public class TestObjectInherited : TestObject
{
[DefaultValue("This is inherited")]
public string InheritedDefaultValue
{
get;
set;
}
[DefaultValue("This is static!")]
public static string StaticProperty
{
get;
set;
}
}
public class TestObject
{
public TestObject()
{
this.InitDefaults();
}
[DefaultValue(-45)]
public int DefaultInt
{
get;
set;
}
[DefaultValue(10.23)]
public double DefaultDouble
{
get;
set;
}
[DefaultValue(true)]
public bool DefaultBool
{
get;
set;
}
[DefaultValue(TestEnum.Value2)]
public TestEnum DefaultEnum
{
get;
set;
}
[DefaultValue("DefaultString!")]
{
get;
set;
}
public string StringWithoutDefault
{
get;
set;
}
public string ValueOfPrivateProperty
{
get
{
return PrivateProperty;
}
}
[DefaultValue("This is a private property!")]
protected string PrivateProperty
{
get;
set;
}
}
public enum TestEnum
{
Value1,
Value2
}
public static class ExtensionsClass
{
/// <summary>
/// Inititializes default values of automatic properties
/// </summary>
/// <param name="o">The o.</param>
public static void InitDefaults(this object o)
{
PropertyInfo[] props = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
for (int i = 0; i < props.Length; i++)
{
PropertyInfo prop = props[i];
if (prop.GetCustomAttributes(true).Length > 0)
{
object[] defaultValueAttribute = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
if (defaultValueAttribute != null)
{
DefaultValueAttribute dva = defaultValueAttribute[0] as DefaultValueAttribute;
if(dva != null)
prop.SetValue(o, dva.Value, null);
}
}
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -