C#:如何使用泛型方法与“out”变量 [英] C#: How to use generic method with "out" variable

查看:354
本文介绍了C#:如何使用泛型方法与“out”变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个简单的泛型函数

$ p $ void分配< T>(out T result)
{
Type type = typeof(T);
if(type.Name ==String)
{
// result =hello;
}
else if(type.Name ==Int32)
{
// result = 100;
}
else result = default(T);
}

用法:

  int value; 
字符串文本;

分配(值); //<<<应将值设为100
赋值(文本); //<<<应该设置文本为你好

我的问题是你如何设置代码来设置这些值,即。在注释部分缺少代码。



感谢您的任何帮助。

解决方案

<看起来在这种情况下,也许你正在试图避免拳击?如果没有更多的信息,很难说,但是对于这个具体的例子来说,使用方法重载会容易得多,并且可能不太容易发生错误:

  void赋值(输出字符串值)
{
// ...
}

void赋值(out int值)
{
// ...
}

出于学习的目的 在这里是错误的,您需要在将对象转换为泛型之前先将值转换为对象:

 (T)(object)hello world!; 

哪个IMO非常讨厌,应该是最后一招 - 当然不会让你的代码更清洁。



任何时候对泛型参数进行类型检查,都可以很好地表明泛型不适合您的问题。参数类型检查会使您的代码更复杂,而不是更简单。它使一种方法负责基于类型的不同行为,而不是一系列易于更改而不会意外影响其他行为的单一方法。请参阅单一责任原则


I want to create a simple generic function

void Assign<T>(out T result) 
{
  Type type = typeof(T);
  if (type.Name == "String")
  {
     // result = "hello";
  }
  else if (type.Name == "Int32")
  {
     // result = 100;
  } 
  else result = default(T);
}

Usage:

int value;
string text;

Assign(value); // <<< should set value to 100
Assign(text); // <<< should set text to "hello"

My question is how do you program the code to set these values ie. the missing codes in comment section.

Thanks for any help.

解决方案

It looks like in this case maybe you're doing it to try to avoid boxing? Difficult to say without more information, but for this specific example, it'd be much easier and probably less bug-prone to just use method overloading:

void Assign(out string value)
{
   //...
}

void Assign(out int value)
{
   //...
}

For the purposes of learning specifically what is wrong here, you do need to cast a value to an object before casting it to the generic type:

(T)(object)"hello world!";

Which IMO is pretty nasty and should be a last resort - certainly doesn't make your code any cleaner.

Any time you do type-checking of generic parameters, it's a good indication generics are not the right solution to your problem. Doing generic parameter type checks makes your code more complex, not simpler. It makes one method responsible for different behaviors based on type, instead of a series of single methods that are easy to change without accidentally affecting the others. See Single Responsibility Principle.

这篇关于C#:如何使用泛型方法与“out”变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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