这个设计在C#中没问题 [英] Is this design okay in C#

查看:65
本文介绍了这个设计在C#中没问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道这是否是良好做法。我想创建一个可以保存字符串或整数的Token类,并处理任何一种类型的标记。我查看了开放式泛型,泛型,摘要,覆盖等,并选择了以下简单的解决方案: -

Just wondering if this is "good practice" or not. I want to create a Token class that can hold a string or an integer, and process tokens of either type. I have looked at open generics, generics, abstracts, overriding etc. and chose simple solution below:-

using System.IO;
using System;

public class Token 
{
    public dynamic Value {get; set;}
}

class Program
{
    static void Main()
    {   
        Token token1;
        Token token2; 
    
        token1 = new Token();
        token2 = new Token();
        
        token1.Value=1;
        token2.Value="hi";
        Console.WriteLine(token1.Value);
        Console.WriteLine(token2.Value);
        token1.Value=token2.Value;
        Console.WriteLine(token1.Value);
        Console.WriteLine(token2.Value);
    }
}





我的尝试:



??如上所述 - 不确定要放在这里?



What I have tried:

?? as above - not sure what to put here ?

推荐答案

这取决于你想用它做什么。也许,我会创建一个抽象的令牌类,并从中派生出更具体的类来表示令牌类型应该做什么,或者用于:

It depends what you want to do with it. Probably, I'd create an abstract Token class, and derive more concrete classes from that to represent what teh token types are supposed to do, or be used for:
public class TokenNumber: Token ...
public class TokenUserName: Token ...

然后我会添加每个派生类必须实现的抽象处理方法。这可能是一个接口而不是一个抽象类,但这取决于你需要用你的标记做什么。

使用动态变量与使用动态变量基本相同一个对象:

I'd then add abstract processing methods which each derived class has to implement. It's possible that this might be an Interface rather than an abstract class, but that would depend on what else you need to do with your Tokens.
Using a Dynamic variable as you are is basically the same as using an object:

public class Token 
{
    public object Value {get; set;}
}

这打败了强类型,这是C#比VB好得多的原因之一。

Which defeats the strong typing that is one of the reasons C# is so much better than VB.


使用你的解决方案,读/写Value需要演员



...

公共对象价值{get;设置;}

...

(int)价值

(字符串)价值



??
Using your solution, the read/write to/from Value would require a cast

...
public object Value {get; set;}
...
(int)Value
(string)Value

??


这篇关于这个设计在C#中没问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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