C#:传递一个通用对象 [英] C# : Passing a Generic Object

查看:122
本文介绍了C#:传递一个通用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个通用的打印功能... PrintGeneric(T)...在以下情况下,我错过什么?



一如往常你的帮助/洞察力赞赏...

 公共接口ITEST 
{}

公共类MyClass1的:ITEST
{
公共字符串MYVAR =你好1;
}

公共类MyClass2:ITEST
{
公共字符串MYVAR =你好2;
}

类DoSomethingClass
{

静态无效的主要()
{
MyClass1的测试1 =新MyClass1的();
MyClass2测试2 =新MyClass2();

Console.WriteLine(test1.var);
Console.WriteLine(test2.var);
Console.WriteLine(test1.GetType());

PrintGeneric(TEST1);
PrintGeneric< test2.GetType()>(测试2);
}

//以下不编译
公共无效PrintGeneric< T>(T检验)
{
Console.WriteLine(通用: + test.myvar);
}
}


解决方案

据不能编译,因为牛逼可以是任何东西,而不是一切都将有 MYVAR 字段。



您可以使 MYVAR 上的属性 ITEST

 公共ITEST 
{
串MYVAR {获得;}
}

和实现它的类作为一个属性:

 公共类MyClass1的:ITEST 
{
公共字符串MYVAR {{返回你好1; }}
}



,然后把一个通用的约束你的方法:



 公共无效PrintGeneric< T>(T检验),其中T:ITEST 
{
Console.WriteLine(通用: + test.myvar);
}



但在这种情况下,说实话你最好只传递一个ITEST

 公共无效PrintGeneric(ITEST测试)
{
Console.WriteLine(通用+ test.myvar);
}


I want to have a generic print function...PrintGeneric(T)...in the following case, what am I missing?

As always your help/insight is appreciated...

public interface ITest
{}

public class MyClass1 : ITest
{
    public string myvar = "hello 1";
}

public class MyClass2 : ITest
{
    public string myvar = "hello 2";
}

class DoSomethingClass
{

    static void Main()
    {
        MyClass1 test1 = new MyClass1();
        MyClass2 test2 = new MyClass2();

        Console.WriteLine(test1.var);
        Console.WriteLine(test2.var);               
        Console.WriteLine(test1.GetType());

        PrintGeneric(test1);
        PrintGeneric<test2.GetType()>(test2);
    }

    // following doesn't compile
    public void PrintGeneric<T>(T test)
    {
        Console.WriteLine("Generic : " + test.myvar);
    }
}

解决方案

It doesn't compile because T could be anything, and not everything will have the myvar field.

You could make myvar a property on ITest:

public ITest
{
    string myvar{get;}
}

and implement it on the classes as a property:

public class MyClass1 : ITest
{
    public string myvar{ get { return "hello 1"; } }
}

and then put a generic constraint on your method:

public void PrintGeneric<T>(T test) where T : ITest
{
    Console.WriteLine("Generic : " + test.myvar);
}

but in that case to be honest you are better off just passing in an ITest:

public void PrintGeneric(ITest test)
{
    Console.WriteLine("Generic : " + test.myvar);
}

这篇关于C#:传递一个通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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