简体   繁体   English

C#,动态返回类型

[英]C#, dynamic return type

What I need is a method that can return a type (no object, cause no casting allowed) following a condition. 我需要的是一个方法,可以在一个条件后返回一个类型(没有对象,导致不允许转换)。 Here is an example: 这是一个例子:

??? right (string fullStr, int endPosition)
{
 string tmpStr = "";

 tmpStr = fullStr.Substring(endPosition);

 if(tmpStr.Length == 1)
   return tmpStr[0]; //return a char!!
 else
   return tmpStr; //return a string!!
}

I tried generics but I was only able to return the type that was coming in, (if a char came in a char was returned, and if a string came in a string was returned). 我尝试了泛型,但我只能返回进入的类型,(如果返回了char中的char,并且返回了字符串中的字符串)。 I tried this: 我试过这个:

    public static T right<T>(T stringToCheck, int endPosition)
    {
        if (typeof(T).ToString() == "System.String")
        {
            string fullString = (string)((object)stringToCheck);
            string response = "";

            response = fullString.Substring(endPosition);

            if (response.Length == 1)
            {

                return (T)((object)response[0]);
            }
            else
                return (T)((object)response);
        }

        return stringToCheck;
    }

I can't use typecasting (returning an object), cant use ref params. 我不能使用类型转换(返回一个对象),不能使用ref params。

Calls to the method have to stay the same: 对方法的调用必须保持不变:

right(stringOrChar,int) -> returns string or char.

Thank You 谢谢

I don't think it's theoretically possible. 我认为这在理论上是不可能的。 You could use "dynamic" in C# 4, but if you're not there yet, you can't do that. 您可以在C#4中使用“动态”,但如果您还没有,那么就不能这样做。

If it could return either a string or a character, then it has to be an object that both of those descend from, of which "object" is your only choice. 如果它可以返回一个字符串或一个字符,那么它必须是一个对象,它们都来自哪个“对象”是你唯一的选择。 And then you'd have to do casts. 然后你必须做演员阵容。

C# (3.5 and previous) needs to know what the single return type of the method is so that it can do checking on the calling method. C#(3.5和之前的版本)需要知道方法的单一返回类型是什么,以便它可以检查调用方法。 And in fact, in C#4, when you say "dynamic" it actually uses "object" underneath. 事实上,在C#4中,当你说“动态”时,它实际上使用了“对象”。

You could create a custom class/struct that has both 您可以创建一个包含两者的自定义类/结构

public class StringOrChar
{
    char charValue;
    string stringValue;
    bool isString;
}

But it's kludgy. 但它很笨拙。

Why do you want to have different return types? 为什么你想要不同的退货类型?

The return type of a function must be typed. 必须键入函数的返回类型。 As with any other variable or operation, any type that inherits from the specified type is a valid return value (which is why object allows anything as a value). 与任何其他变量或操作一样,从指定类型继承的任何类型都是有效的返回值(这就是object允许任何值作为值的原因)。

The logistics of the caller wouldn't make much sense; 来电者的后勤工作没有多大意义; how would you know whether to type your variable as a char or a string in your example? 您如何知道在示例中是否将变量键入为charstring

Is there a particular reason that you can't return a string in all cases? 是否有特殊原因导致您无法在所有情况下返回string

Your can use out parameters. 你可以out参数。 or return a type that contains both variations. 或返回包含两种变体的类型。

there are alot of " left(str,1) < 'x' " but other times it is simply abc = left(str,3) 有很多“左(str,1)<'x'”但其他时候它只是abc = left(str,3)

In this particular case, you could just return a single-character string. 在这种特殊情况下,您只需返回单字符字符串即可。 Comparing strings operates on their lexicographical order, so there's no specific need to use chars here (unless, of course, the original author was using polymorphism to treat the chars differently from strings, in which case you have my sympathies). 比较字符串按照字典顺序进行操作,因此这里没有特别需要使用字符(当然,除非原始作者使用多态来将字符与字符串区别对待,在这种情况下,您有我的同情心)。

methods can only - as far as i know - return one type 方法只能 - 据我所知 - 返回一种类型

so return object and cast is the logical alternative 所以返回对象和强制转换是合乎逻辑的选择

however, note that if your design has forced you into this predicament, there may be a flaw in it; 但请注意,如果你的设计迫使你陷入这种困境,那么它可能存在缺陷; perhaps some more details can help us help you 或许更多细节可以帮助我们

note: jon skeet is immune from all such restrictions 注意:jon双向飞碟免受所有这些限制

What about this: 那这个呢:

string right(string fullStr, int endPosition, out bool oneChar)
{ 
    string result = fullStr.Substring(endPosition); 
    oneChar = result.Length == 1;
    return result;
}

Enriquev, Enriquev,

There is not a way to implement the right without changing the syntax from VBA. 如果不改变VBA的语法,就无法实现权利 You could specify what return type you wanted, but this is essentially casting... 你可以指定你想要的返回类型,但这基本上是铸造......

public static U right<T, U>(T input, int index)
{
...
return (U)returnVariable;
}

I don't really think this solves your problem. 我真的不认为这可以解决你的问题。

Is it possible to do a regex replace of all single characters surrounded by single quotes? 是否可以对单引号括起的所有单个字符进行正则表达式替换? This will make the characters into strings and allow your comparison operators to work. 这将使字符成为字符串并允许比较运算符工作。

This should work: 这应该工作:

    public static dynamic right(string fullStr, int endPosition)
    {
        string tmpStr = "";

        tmpStr = fullStr.Substring(endPosition);

        if (tmpStr.Length == 1)
            return tmpStr[0]; //return a char!!
        else
            return tmpStr; //return a string!!
    }

Testing this code: 测试此代码:

    static void Main(string[] args)
    {
        var str = right("Hello", 3);
        Console.WriteLine(str.GetType()); // System.String

        var ch = right("Hello", 4);
        Console.WriteLine(ch.GetType()); // System.Char
    }

Are you trying to do this? 你想这样做吗?

/// <summary>
/// Emulates VB Right Function
/// Returns a string containing a specified number of characters from the right side of a string.
/// </summary>
/// <param name="s"></param>
/// <param name="length">The number of characters to return.</param>
/// <returns>
/// The right <paramref name="length"/> number of characters from the string.
/// If the string has less than or equal to <paramref name="length"/> number of characters,
/// an empty string is returned.
/// </returns>
public static string Right(this string s, int length)
{
    return length > s.Length ? string.Empty : s.Substring(s.Length - length);
}

When calling this method, you could do: 调用此方法时,您可以执行以下操作:

string myString = "Test String";
string returnedString = mystring.Right(1);
char? myChar = returnedString.Length == 1 ? returnedString[0] : null;
bool isReturnValueAChar = myChar.HasValue;

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

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