[英]How to convert the current class name of asp.net usercontrols to string on c#?
So I have tried GetType() but for some reason, It does include the namespace... 所以我尝试了GetType(),但由于某种原因,它确实包含了命名空间......
Does C# not have a property for a class specifying its name? C#没有指定其名称的类的属性吗?
For example: 例如:
public class Parent : System.Web.UI.UserControl {
public someFunction(){
Child child = new Child();
Console.WriteLine(child.ThePropertyThatContainsTheName);
}
}
public class Child : Parent {
}
I have tried to create the Child with a string property that has the name hard-coded, but only if we could find a better workaround to this... maybe reflection or expressions... 我曾尝试使用名称为硬编码的字符串属性创建Child,但前提是我们可以找到更好的解决方法...也许是反射或表达式......
Thanks in advance =) 在此先感谢=)
Edit: I am working on user controls by the way... 编辑:顺便说一下我正在处理用户控件...
If you are using an ASP.NET Web Application project, you will normally be using the code-behind model. 如果您使用的是ASP.NET Web应用程序项目,则通常会使用代码隐藏模型。
ASP.NET will dynamically generate and compile a class from your aspx/ascx file, which uses the class you defined in your code-behind file as a base class. ASP.NET将从您的aspx / ascx文件动态生成和编译一个类,该文件使用您在代码隐藏文件中定义的类作为基类。
this.GetType().Name
and this.GetType().FullName
will return the name of the auto-generated class generated by ASP.NET. this.GetType().Name
和this.GetType().FullName
将返回ASP.NET生成的自动生成的类的名称。 This auto-generated class will subclass the UserControl/WebPage class you have defined in your code-behind file ( Inherits
keyword in the <%@Control ...>
tag of your ascx file / <%@Page ...>
tag of your aspx file). 这个自动生成的类将子类化您在代码隐藏文件中定义的UserControl / WebPage类(在ascx文件的
<%@Control ...>
标记中的Inherits
关键字/ <%@Page ...>
标记你的aspx文件)。
If you want the name of your code-behind class, use: 如果您想要代码隐藏类的名称,请使用:
this.GetType().BaseType.Name
or this.GetType().BaseType.FullName
this.GetType().BaseType.Name
或this.GetType().BaseType.FullName
Use Type.Name
like this: 像这样使用
Type.Name
:
using System;
class Test
{
static void Main()
{
Console.WriteLine(typeof(Test).Name);
}
}
or like this (if you are getting the type via Object.GetType
): 或者像这样(如果你通过
Object.GetType
获取类型):
using System;
class Foo { }
class Test
{
static void Main()
{
Foo foo = new Foo();
Console.WriteLine(foo.GetType().Name);
}
}
Use GetType()
and Name
使用
GetType()
和Name
Console.Writeline(child.GetType().Name);
or 要么
Console.Writeline(child.GetType().FullName);
Or you can use reflection to get base type of your variable 或者您可以使用反射来获取变量的基本类型
control.GetType().BaseType.Name
If you need I can provide deep description why it is so. 如果您需要,我可以提供深刻的描述为什么会如此。
If you want you can try this code 如果你想要,你可以尝试这个代码
System.IO.Path.GetFileNameWithoutExtension(((UserControl)control).AppRelativeVirtualPath)
This will give you the name you want, but this is not the type of the UserControl but it's file name. 这将为您提供所需的名称,但这不是UserControl的类型,而是文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.