csharp: Use of Is and As operators in csharp
/// <summary>
/// Geovin Du 20170622
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Object o = new Object();
System.Boolean b1 = (o is System.Object);//b1 为true
System.Boolean b2 = (o is Employee);//b2为false if (o is Employee)
{
Employee em = (Employee)o;
em.RealName = "geovindu";
MessageBox.Show(em.RealName);
}
else
{
MessageBox.Show("no"); //结果为显示NO
}
Object obj;
Employee employee = new Employee();
employee.RealName = "du";
employee.Birthday = DateTime.Now;
employee = o as Employee;
obj = o as Employee; if (employee != null)
{
//在if语句中使用e
MessageBox.Show(employee.RealName);
}
else
{
MessageBox.Show("no2"); //结果为显示NO2
} }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
var c1 = "";
var c2 = typeof(string);
object oc1 = c1;
object oc2 = c2; var s1 = 0;
var s2 = '.';
object os1 = s1;
object os2 = s2; bool b = false; Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
b = c1.GetType() == typeof(string); // ~60ms
b = c1 is string; // ~60ms b = c2.GetType() == typeof(string); // ~60ms
b = c2 is string; // ~50ms b = oc1.GetType() == typeof(string); // ~60ms
b = oc1 is string; // ~68ms b = oc2.GetType() == typeof(string); // ~60ms
b = oc2 is string; // ~64ms b = s1.GetType() == typeof(int); // ~130ms
b = s1 is int; // ~50ms b = s2.GetType() == typeof(int); // ~140ms
b = s2 is int; // ~50ms b = os1.GetType() == typeof(int); // ~60ms
b = os1 is int; // ~74ms b = os2.GetType() == typeof(int); // ~60ms
b = os2 is int; // ~68ms b = GetType1<string, string>(c1); // ~178ms
b = GetType2<string, string>(c1); // ~94ms
b = Is<string, string>(c1); // ~70ms b = GetType1<string, Type>(c2); // ~178ms
b = GetType2<string, Type>(c2); // ~96ms
b = Is<string, Type>(c2); // ~65ms b = GetType1<string, object>(oc1); // ~190ms
b = Is<string, object>(oc1); // ~69ms b = GetType1<string, object>(oc2); // ~180ms
b = Is<string, object>(oc2); // ~64ms b = GetType1<int, int>(s1); // ~230ms
b = GetType2<int, int>(s1); // ~75ms
b = Is<int, int>(s1); // ~136ms b = GetType1<int, char>(s2); // ~238ms
b = GetType2<int, char>(s2); // ~69ms
b = Is<int, char>(s2); // ~142ms b = GetType1<int, object>(os1); // ~178ms
b = Is<int, object>(os1); // ~69ms b = GetType1<int, object>(os2); // ~178ms
b = Is<int, object>(os2); // ~69ms
} sw.Stop();
MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
}
/// <summary>
///
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
static bool GetType1<S, T>(T t)
{
return t.GetType() == typeof(S);
}
/// <summary>
///
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
static bool GetType2<S, T>(T t)
{
return typeof(T) == typeof(S);
}
/// <summary>
///
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
static bool Is<S, T>(T t)
{
return t is S;
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
var cl1 = new Class1();
if (cl1 is IFormatProvider)
{
MessageBox.Show("cl1 is IFormatProvider ok");
}
else
{
MessageBox.Show("cl1 is IFormatProvider no");
}
if (cl1 is Object)
{
MessageBox.Show("cl1 is Object ok");
}
else
{
MessageBox.Show("cl1 is Object no");
}
if (cl1 is Class1)
{
MessageBox.Show("cl1 is Class1 ok");
}
else
{
MessageBox.Show("cl1 is Class1 no");
}
if (cl1 is Class2)
{
MessageBox.Show("cl1 is Class2 ok");
}
else
{
MessageBox.Show("cl1 is Class2 no");
} var cl2 = new Class2();
if (cl2 is IFormatProvider)
{
MessageBox.Show("cl2 is IFormatProvider ok");
}
else
{
MessageBox.Show("cl2 is IFormatProvider no");
}
if (cl2 is Class2)
{
MessageBox.Show("cl2 is Class2 ok");
}
else
{
MessageBox.Show("cl2 is Class2 no");
}
if (cl2 is Class1)
{
MessageBox.Show("cl2 is Class1 ok");
}
else
{
MessageBox.Show("cl2 is Class1 no");
} Class1 cl = cl2;
if (cl is Class1)
{
MessageBox.Show("cl is Class1 ok");
}
else
{
MessageBox.Show("cl is Class1 no");
};
if(cl is Class2)
{
MessageBox.Show("cl is Class2 ok");
}
else
{
MessageBox.Show("cl is Class2 no");
}; bool isc1 = (cl is Class1);
if (isc1)
{
MessageBox.Show("true");
} }
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
Object o = new Person("Jane");
ShowValue(o); o = new Dog("Alaskan Malamute");
ShowValue(o); Employee em = new Employee();
em.RealName = "geovindu";
em.Birthday = DateTime.Now;
o =em;
ShowValue(o);
}
/// <summary>
///
/// </summary>
/// <param name="o"></param>
public static void ShowValue(object o)
{
if (o is Person)
{
Person p = (Person)o;
MessageBox.Show(p.Name);
}
else if (o is Dog)
{
Dog d = (Dog)o;
MessageBox.Show(d.Breed);
}
else
{
MessageBox.Show("啥也不是");
}
} }
/// <summary>
///
/// </summary>
public class Class1 : IFormatProvider
{
public object GetFormat(Type t)
{
if (t.Equals(this.GetType()))
return this;
return null;
}
}
/// <summary>
///
/// </summary>
public class Class2 : Class1
{
public int Value { get; set; }
}
/// <summary>
/// 员工
/// </summary>
public class Employee
{
/// <summary>
/// 真名
/// </summary>
public string RealName { set; get; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime Birthday { set; get; }
}
/// <summary>
///
/// </summary>
public struct Person
{
public string Name { get; set; } public Person(string name)
: this()
{
Name = name;
}
}
/// <summary>
///
/// </summary>
public struct Dog
{
public string Breed { get; set; } public Dog(string breedName)
: this()
{
Breed = breedName;
}
}
TypeInfo,PropertyInfo,MethodInfo,FieldInfo
/// <summary>
/// Geovin Du 涂聚文
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
Int32 indent = 0;
// Display information about each assembly loading into this AppDomain.
foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
{
Display(indent, "Assembly: {0}", b); // Display information about each module of this assembly.
foreach (Module m in b.GetModules(true))
{
Display(indent + 1, "Module: {0}", m.Name);
} // Display information about each type exported from this assembly. indent += 1;
foreach (Type t in b.GetExportedTypes())
{
Display(0, "");
Display(indent, "Type: {0}", t); // For each type, show its members & their custom attributes. indent += 1;
foreach (MemberInfo mi in t.GetMembers())
{
Display(indent, "Member: {0}", mi.Name);
DisplayAttributes(indent, mi); // If the member is a method, display information about its parameters. if (mi.MemberType == MemberTypes.Method)
{
foreach (ParameterInfo pi in ((MethodInfo)mi).GetParameters())
{
Display(indent + 1, "Parameter: Type={0}, Name={1}", pi.ParameterType, pi.Name);
}
} // If the member is a property, display information about the property's accessor methods.
if (mi.MemberType == MemberTypes.Property)
{
foreach (MethodInfo am in ((PropertyInfo)mi).GetAccessors())
{
Display(indent + 1, "Accessor method: {0}", am);
}
}
}
indent -= 1;
}
indent -= 1;
}
} /// <summary>
/// Displays the custom attributes applied to the specified member.
/// </summary>
/// <param name="indent"></param>
/// <param name="mi"></param>
public static void DisplayAttributes(Int32 indent, MemberInfo mi)
{
// Get the set of custom attributes; if none exist, just return.
object[] attrs = mi.GetCustomAttributes(false);
if (attrs.Length == 0) { return; } // Display the custom attributes applied to this member.
Display(indent + 1, "Attributes:");
foreach (object o in attrs)
{
Display(indent + 2, "{0}", o.ToString());
}
}
/// <summary>
/// Display a formatted string indented by the specified amount.
/// </summary>
/// <param name="indent"></param>
/// <param name="format"></param>
/// <param name="param"></param>
public static void Display(Int32 indent, string format, params object[] param)
{
string st = new string(' ', indent * 2);
MessageBox.Show(st);
string s=string.Format("format:{0},param:{1}.",format, param);
MessageBox.Show(s);
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button6_Click(object sender, EventArgs e)
{
// System.Reflection.MemberTypes
//4.6,4.5 .net
//TypeInfo t = typeof(Calendar).GetTypeInfo();
//4.6,4.5
// IEnumerable<PropertyInfo> pList = t.DeclaredProperties;
//4.5,4.6
//IEnumerable<MethodInfo> mList = t.DeclaredMethods; //4.0
IEnumerable<PropertyInfo> pList = typeof(Calendar).GetProperties();
IEnumerable<MethodInfo> mList = typeof(Calendar).GetMethods();
IEnumerable<FieldInfo> fList = typeof(Calendar).GetFields(); StringBuilder sb = new StringBuilder();
sb.Append("Properties:");
foreach (PropertyInfo p in pList)
{ sb.Append("\n" + p.DeclaringType.Name + ": " + p.Name);
}
sb.Append("\nMethods:");
foreach (MethodInfo m in mList)
{
sb.Append("\n" + m.DeclaringType.Name + ": " + m.Name);
}
MessageBox.Show(sb.ToString());
}
csharp: Use of Is and As operators in csharp的更多相关文章
- What's Assembly - CSharp - Editor - first pass.dll? Best How to Fix Assembly - CSharp - Editor - first pass.dll Error Guide
If you've found yourself here, I'm guessing that you're getting Assembly - CSharp - Editor - first p ...
- 德卡Z90读卡器读取社保卡,德卡Z90读卡器CSharp示例程序源码
前言,最近学习调用 医保卡业务,使用德卡读卡器,主要就是调用一个DLL,动态库文件. 借着自学的机会把心得体会都记录下来,方便感兴趣的小伙伴学习与讨论. 内容均系原创,欢迎大家转载分享,但转载的同时别 ...
- CSharp使用ANTLR4生成简单计算Parser
ANTLR简介 ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, pr ...
- VS2012中丢失ArcGIS模板的解决方法
VS2012中丢失ArcGIS模板的解决方法 由于ArcGIS10.0(for .NET)默认是用VS2010作为开发工具的,所以在先安装VS2012后装ArcGIS10.0 桌面版及ArcObjec ...
- C# EF增删改查
1.增 //1.创建一个EF数据上下文对象 MyDBEntities context=new MyDBEntities(); //2.将要添加的数据,封装成对象 Users user = new Us ...
- Python字符串格式化
一.使用格式化符来格式化字符串: Python支持的所有格式化符 格式化符 意义 'd' 返回要格式化对象的十进制表示,如果可以 'i' 返回要格式化对象的十进制表示,如果可以 'o' 返回要格式化对 ...
- mvc Razor 视图中找不到 ViewBag的定义
在Razor 视图中,我们有时会看到 ViewBag.Title 下会划一个红线,当鼠标放上去的时候会提示这样的一个错误: 找不到编译动态表达式所需的一种或多种类型,是否缺少引用? 但在项目启动运行时 ...
- 在VisualStudio2012环境下安装ArcEngine 10.0
因为ArcEngine10.0默认对应的开发工具为VS2010,在安装了VS2012的情况下安装ArcEngine10.0(注意:我自己的环境为VS2012和ArcEngine10.0,对于其他版本在 ...
- 使用XmlHelper添加节点C#代码
接着上一篇:http://keleyi.com/a/bjac/ttssua0f.htm在前篇文章中,给出了C# XML文件操作类XmlHelper的代码,以及使用该类的一个例子,即使用XmlHelpe ...
随机推荐
- Android开发 - 更"聪明"的申请权限方式
在Android6.0以后,很多权限需要动态申请,只有在用户点同意后,我们才能使用对应API,因此,正确申请权限就显得很重要. 常用方式 通常我们使用这种方式来判断权限状态: private stat ...
- 菜刀(代码执行)函数和命令执行函数详解及Getshell方法
i春秋作家:大家奥斯的哦 原文来自:https://bbs.ichunqiu.com/thread-41471-1-1.html 代码执行函数 VS 命令执行函数 一直想整理这两块的内容,但是一直没时 ...
- Android 开发常用版本控制命令
1. git 回退到指定版本 // 使用git log命令查看所有的历史版本,获取某个历史版本的id,假设查到历史版本的id是139dcfaa558e3276b30b6b2e5cbbb9c00bbdc ...
- centoos内核升级
1.检查当前CentOS内核版本 uname -r 2.导入key 打开http://elrepo.org/tiki/tiki-index.php 复制执行该命令 3.安装ELRepo 打开2步中的网 ...
- HTML+CSS实现页面豆腐块布局和图片居中
<!DOCTYPE html> <html> <head lang="en"> <meta http-equiv="Conten ...
- 启动elasticsearch报错
could not find java; set JAVA_HOME or ensure java is in PATH 首先需要安装java 1.yum list installed |grep j ...
- conda环境里安装pydot
一.conda环境里安装pydot, 输入以下命令即可: conda install -c anaconda pydot 二.如果运行tensorflow,提示缺什么包,都可以在这里下载. ----- ...
- 课程四(Convolutional Neural Networks),第一周(Foundations of Convolutional Neural Networks) —— 1.Practice questions:The basics of ConvNets
[解释] 100*(300*300*3)+ 100=27000100 [解释] (5*5*3+1)*100=7600 [中文翻译] 您有一个输入是 63x63x16, 并 将他与32个滤波器卷积, 每 ...
- pythonic(fork)
转载 https://wuzhiwei.net/be_pythonic/
- php扩展编译方法
linux下php已经编译,如何再为php增加新的扩展通过php自带的phpize,如我的phpize在/usr/local/php/bin/phpize1.到软件的官方或pecl.php.net去下 ...