如果我声明了类MyClass,那么当创建像MyClass obj = new MyClass()的对象时,我没有收到任何错误;为什么? [英] If I declared class MyClass,am not getting any error when created object like MyClass obj=new MyClass(); Why?

查看:191
本文介绍了如果我声明了类MyClass,那么当创建像MyClass obj = new MyClass()的对象时,我没有收到任何错误;为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



 名称空间 MyNamespace 
{
public class MyClass< string>
{
// 我的代码在这里
}
public class 演示
{
public static void main()
{
MyClass< ; INT> obj = new MyClass< int>();
}
}
}





如果我创建了这样的对象,它没有给出错误为什么?这究竟是什么意思?



如果我创建类似



  public   class  MyClass< t> 
{
// 我的代码在这里
}





意味着动态我们可以将任何类型传递给使用类型为T的成员,除此之外还有其他原因吗?我对此感到困惑吗?



谢谢你

解决方案

在'冒险'进入<$ c $之前c> Generics land,我强烈建议你阅读一些文档。您可以开始,例如: C#Generics简介 [ ^ ]。


这应该给出错误,你不允许这样做

  public   class  MyClass< string> 





类型参数声明必须是标识符,而不是类型。



再次检查您要编译的内容以确保实际编译你认为你是什么。



希望这会有所帮助,

Fredrik


参考 - [MSDN]泛型(C#编程指南) [ ^ ]

引用:

泛型被添加到C#语言的2.0版和通用语言中运行时(CLR)。泛型向.NET Framework引入了类型参数的概念,这使得设计类和方法成为可能,这些类和方法推迟一个或多个类型的规范,直到通过客户端代码声明和实例化类或方法。例如,通过使用泛型类型参数T,您可以编写其他客户端代码可以使用的单个类,而不会产生运行时强制转换或装箱操作的成本或风险,如下所示:


Hi All

namespace MyNamespace
{
    public class MyClass<string>
    {
        //my code goes here
    }
    public class Demo
    {
        public static void main()
        {
            MyClass<int> obj = new MyClass<int>();
        }
    }
}



if I created object like this, it is not giving error why? what does it mean exactly?

if I created class like

public class MyClass<t>
{
    //my code goes here
}



means dynamically we can pass any type to members which uses type as "T", apart from this is there any other reason? am getting confusion on this?

Thank u

解决方案

Before 'adventuring' into Generics land, I strongly advice you reading some documentation. You may start, for instance with: An Introduction to C# Generics[^].


That should give an error, you're not allowed to do

public class MyClass<string>



The type parameter declaration must be an identifier, not a type.

Check what you're compiling again to make sure you're actually compiling what you think you are.

Hope this helps,
Fredrik


Refer - [MSDN] Generics (C# Programming Guide)[^]

Quote:

Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:


这篇关于如果我声明了类MyClass,那么当创建像MyClass obj = new MyClass()的对象时,我没有收到任何错误;为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆