简体   繁体   English

如何在.ASPX文件中声明和使用C#对象?

[英]How do i declare and use a C# object in an .ASPX file?

i am making a website using asp.net and C# and well i got stuck at the first hurdle, i found out that to use code you use the <% %> with asp but i dont get how i would create an object of my class to use in the aspx file? 我正在使用asp.net和C#创建一个网站,但是我遇到了第一个障碍,我发现要使用代码对ASP使用<%%>,但是我不知道如何创建类的对象在aspx文件中使用?

I think its syntax more than anything i cant seem to get to work. 我认为它的语法比我似乎无法使用的要多。

Thanks, 谢谢,

Ash

If you need to declare a global object to be accessible everywhere in your page: 如果您需要声明一个全局对象,使其可以在页面的任何位置访问:

<script runat="server">
   // ObjectType: Your class name
   // Name: Your instance (variable) name.
   ObjectType Name = new ObjectType();
</script>

If you just need a local variable: 如果只需要局部变量:

<%
   ObjectType name = new ObjectType();
   name.SomeMethod();
%>

By the way, you should have good reasons for using these kind of things in ASP.NET. 顺便说一句,您应该有充分的理由在ASP.NET中使用这些东西。 There are usually better ways to encapsulate user interface elements in user controls and master pages. 通常,有更好的方法可以将用户界面元素封装在用户控件和母版页中。

Side note: You can't use using directives in .aspx files. 旁注: .aspx文件中不能使用using指令。 If you need to import some namespace in your code, you should add <%@ Imports Namespace="SomeNamespace" %> directives right after your <%@ Page %> directive. 如果需要在代码中导入某些名称空间,则应在<%@ Page %>指令之后添加<%@ Imports Namespace="SomeNamespace" %> <%@ Page %>指令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM