自定义转换

using System;
using System.Collections.Generic;

class Person
{
public int Age;
public static explicit operator int(Person p)
{
return p.Age;
}
}


public class MyClass
{


public static void RunSnippet()
{
int i = 10;
Person p = new Person();
p.Age = 30;

i = (int) p;
Console.WriteLine(i);
}

#region Helper methods

public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("--- The following error occurred while executing the snippet: {0} ---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}

private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}

private static void RL()
{
Console.ReadLine();
}

private static void Break()
{
System.Diagnostics.Debugger.Break();
}

#endregion
}

原文地址:https://www.cnblogs.com/jinweijie0527/p/4970878.html