page contents

C#中使用typeof Java关键字和GetType()获取类的内部结构

本文讲述了C#中使用typeof Java关键字和GetType()获取类的内部结构!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

attachments-2022-11-5fskn0Kb637d7f18acfc6.jpg本文讲述了C#中使用typeof Java关键字和GetType()获取类的内部结构!具有很好的参考价值,希望对大家有所帮助。一起跟随六星小编过来看看吧,具体如下:

java有反射机制,C#也有反射机制,在C#中typeof关键字用于获取类型的System.Type对象,该对象的GetMethods()方法可以得到类型中定义的方法对象的计集合,调用方法集合中每个方法对象的GetParameters()可以得到每个方法的参数集合,但是需要引用Reflection命名空间。

获取System.Type对象有两种方法:第一种是用typeof关键字,第二种是用对象引用调用GetType()方法

1、System.Type type =  typeof(System.Int32);   //参数是一种系统类型

2、 string str= “test”;

System.Type type = str.GetType();    //用对象引用调用GetType()方法

二、解决步骤

1、在代码中引用Reflection命名空间

using System.Reflection;

2、可以用typeof关键字,也可以用GetType()方法获取类的内部结构

三、代码演示

1、获取String类的的所有方法和参数并显示。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection; namespace test1
{
public partial class Form7 : Form
{
public Form7()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
//Type type = typeof(System.String);
String str = "test";
Type type = str.GetType();
foreach (MethodInfo method in type.GetMethods())
{
out_rtb.AppendText("方法名称:"+method.Name+Environment.NewLine);
foreach (ParameterInfo param in method.GetParameters())
{
out_rtb.AppendText("\t参数:" + param.Name + Environment.NewLine);
}
}
}
}
}

2、提示错误信息后,将所有CheckBox控件内容清空

attachments-2022-11-hvzOmOlx637d7eb5b82e3.jpg

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection; namespace test1
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
} private void button1_Click(object sender, EventArgs e)
{
byte input1,input2;
if (byte.TryParse(input1_tbx.Text, out input1) && byte.TryParse(input2_tbx.Text, out input2))
{
try
{
checked
{
input1 += input2;
}
result_tbx.Text = input1.ToString();
}
catch (OverflowException ex)
{
MessageBox.Show(ex.Message, "错误信息");
}
}
else
{
MessageBox.Show("请输入小于255的数字!", "提示信息");
} //清空输入信息
foreach (Control c in Controls)
{
if (c.GetType() == typeof(TextBox))
{
((TextBox)c).Clear();
}
}
} }
}

更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。

想高效系统的学习Python编程语言,推荐大家关注一个微信公众号:Python编程学习圈。每天分享行业资讯、技术干货供大家阅读,关注即可免费领取整套Python入门到进阶的学习资料以及教程,感兴趣的小伙伴赶紧行动起来吧。

attachments-2022-05-rLS4AIF8628ee5f3b7e12.jpg

  • 发表于 2022-11-23 10:02
  • 阅读 ( 223 )
  • 分类:C/C++开发

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
轩辕小不懂
轩辕小不懂

2403 篇文章

作家榜 »

  1. 轩辕小不懂 2403 文章
  2. Pack 1131 文章
  3. 小柒 1038 文章
  4. Nen 576 文章
  5. 王昭君 209 文章
  6. 文双 71 文章
  7. 小威 64 文章
  8. Cara 36 文章