标签: generic-method

通用方法和可选参数

是否有可能写出类似的结构?
我想以某种方式设置类型T的参数的默认值.

    private T GetNumericVal<T>(string sColName, T defVal = 0)
    {
        string sVal = GetStrVal(sColName);
        T nRes;
        if (!T.TryParse(sVal, out nRes))
            return defVal;

        return nRes;
    }
Run Code Online (Sandbox Code Playgroud)

另外,我发现以下链接: 通用类型转换FROM字符串
我认为,此代码必须工作

private T GetNumericVal<T>(string sColName, T defVal = default(T)) where T : IConvertible
{
    string sVal = GetStrVal(sColName);
    try
    {
        return (T)Convert.ChangeType(sVal, typeof(T));
    }
    catch (FormatException)
    {
        return defVal;
    }            
}
Run Code Online (Sandbox Code Playgroud)

c# generic-method optional-arguments

13
推荐指数
2
解决办法
4771
查看次数

为什么参数的私有字段对Java 6中的泛型方法可见,但在Java 7中却不可见?

可能重复:
升级到Java 7后,泛型类的类型参数化字段变为不可见

public class Test{

    private String _canYouSeeMe = "yes";

    <T extends Test> void genericMethod(T hey){
        String s = hey._canYouSeeMe;
    }

    void method(Test hey){
        String s = hey._canYouSeeMe;
    }   
}
Run Code Online (Sandbox Code Playgroud)

在针对JDK 1.6构建时,这种编译很好但是对于1.7,在genericMethod()中存在编译器错误:字段Test._canYouSeeMe不可见

可以通过使_canYouSeeMe受保护而不是私有来解决错误,但我只是想知道从1.6到1.7的变化

java generics private-members generic-method java-7

13
推荐指数
1
解决办法
867
查看次数

通用方法处理IEnumerable与泛型类型不同

请检查以下代码段:

public interface ICountable { }
public class Counter<T>
    where T : ICountable
{
    public int Count(IEnumerable<T> items)
    {
        return 0;
    }

    public int Count(T Item)
    {
        return 0;
    }
}

public class Counter
{
    public int Count<T>(IEnumerable<T> items)
        where T : ICountable
    {
        return 0;
    }

    public int Count<T>(T Item)
        where T : ICountable
    {
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

Counter的两个版本仅在泛型参数的规范上有所不同.其中一个定义为泛型类型参数,另一个定义为泛型参数.两者都限制方法参数以实现ICountable接口.我将分别称他们为具体非具体.

现在,我定义了一个实现ICountable接口的类,以及一组实例:

public class CItem : ICountable { }
var countables = new List<CItem>(); …
Run Code Online (Sandbox Code Playgroud)

.net c# generics generic-type-argument generic-method

10
推荐指数
1
解决办法
967
查看次数

运算符'&'不能应用于'T'和'T'类型的操作数

我的应用程序定义了几个enum包含该[Flags]属性的s .

我想写一个小的实用程序方法来检查是否为这些中enum的任何一个设置了标志,我想出了以下内容.

protected static bool IsFlagSet<T>(ref T value, ref T flags)
{
    return ((value & flags) == flags);
}
Run Code Online (Sandbox Code Playgroud)

但这给了我错误"运算符'&'不能应用于'T'和'T'类型的操作数".

这可以使用吗?

c# generics generic-method

9
推荐指数
3
解决办法
4223
查看次数

C#:如何使用带有"out"变量的泛型方法

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

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);
}
Run Code Online (Sandbox Code Playgroud)

用法:

int value;
string text;

Assign(value); // <<< should set value to 100
Assign(text); // <<< should set text to "hello"
Run Code Online (Sandbox Code Playgroud)

我的问题是如何编写代码来设置这些值,即.评论部分中缺少的代码.

谢谢你的帮助.

c# generics out-parameters generic-method

8
推荐指数
1
解决办法
5621
查看次数

Java:在匿名类中定义泛型方法

以下java代码工作正常.

public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        JButton f(JButton x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

如果该方法更改为其通用形式,则程序将失败.

public static void main(String[] arg){
    JPanel p = (new JPanel());
    p.add( new Object(){
        <T> T f(T x){
            x.setEnabled(false);
            return x;
        }}.f(new JButton("B")) );
    JFrame w = new JFrame("W");
    w.add(p);
    w.pack();
    w.setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

为什么会失败?如何在匿名类中定义泛型方法?

这个问题是出于学习目的.

java anonymous-class generic-method

8
推荐指数
2
解决办法
1034
查看次数

如何在非泛型.NET类型上获取泛型方法的MethodInfo?

我有这个小问题,我无法弄清楚要传递给Type.GetMethod的哪些参数,以便在非泛型类型上返回泛型方法的MethodInfo.具体来说,我有这种类型的定义:

public static class A
{
  public static B F<T>(bool dummy)
  {
  }
  public static B F<T>(IEnumerable<T> arg)
  {
  ...
  }
}
Run Code Online (Sandbox Code Playgroud)

我在Type.GetMethod上尝试了几次,但没有人会返回F方法的MethodInfo.

我知道我可以调用Type.GetMethods甚至Type.FindMember,但我对Type.GetMethod感兴趣.

有任何想法吗?

谢谢.

编辑

实际上,我的代码有点复杂.泛型方法被重载,因此我不能仅使用函数名称来使用Type.GetMethod.我试过这些变种:

typeof(A).GetMethod("F", BindingFlags.Static | BindingFlags.Public, null, new Type[]{ typeof(IEnumerable<>) }, null)
typeof(A).GetMethod("F`1", BindingFlags.Static | BindingFlags.Public, null, new Type[]{ typeof(IEnumerable<>) }, null)
typeof(A).GetMethod("F[T]", BindingFlags.Static | BindingFlags.Public, null, new Type[]{ typeof(IEnumerable<>) }, null)
typeof(A).GetMethod("F[[T]]", BindingFlags.Static | BindingFlags.Public, null, new Type[]{ typeof(IEnumerable<>) }, null)
Run Code Online (Sandbox Code Playgroud)

.net reflection methodinfo generic-method

7
推荐指数
2
解决办法
7200
查看次数

如何将Generic方法中的参数同时分配给Integer和Character类?

为什么这段代码没有显示任何编译错误?

public class Generic
{
    public static void main(String[] args)
    {
        Character[] arr3={'a','b','c','d','e','f','g'};
        Integer a=97;
        System.out.println(Non_genre.genMethod(a,arr3));
    }
}

class Non_genre
{
    static<T> boolean genMethod(T x,T[] y)
    {
        int flag=0;
        for(T r:y)
        {
            if(r==x)
                flag++;
        }
        if(flag==0)
            return false;
        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我们写这样的普通代码(如下所示)

public class Hello
{
    public static void main(String[] args)
    {
        Character arr=65;
        Integer a='A';
        if(arr==a)  //Compilation Error,shows Incompatible types Integer and Character
            System.out.println("True");
    }
}   
Run Code Online (Sandbox Code Playgroud)

那么为什么上面的上面运行正常,T怎么可能是Integer类和T的数组同时是Character类,如果它运行那么为什么它不打印为true,'a'的ASCII vaue是97,所以它应该打印真实.

java generics integer character generic-method

7
推荐指数
1
解决办法
105
查看次数

泛型方法如何在C#中实例化?

假设我有一个通用方法:

void Fun<T>(FunArg arg) {}
Run Code Online (Sandbox Code Playgroud)

this.Fun<Feature>this.Fun<Category>通用方法的不同实例?

一般来说,泛型方法如何实例化?不同的泛型参数会产生不同的方法,或者同一个方法以及在运行时使用的不同元数据?

请使用语言规范中的一些引用来支持您的回答.

另外,假设我做了这些:

client.SomeEvent += this.Fun<Feature>;   //line1
client.SomeEvent += this.Fun<Category>;  //line2
client.SomeEvent += this.Fun<Result>;    //line3
Run Code Online (Sandbox Code Playgroud)

然后,

client.SomeEvent -= this.Fun<Feature>;   //lineX
Run Code Online (Sandbox Code Playgroud)

是否lineX取消我在做的事情line1?或者它还取决于其他人呢?

c# generics generic-method

6
推荐指数
2
解决办法
170
查看次数

使用反射查找泛型方法时发现不明确的匹配

我正在使用反射来查找 Newtonsoft 的泛型方法,JsonConvert.DeserializedObject<T>但我发现它返回了非泛型版本的不明确匹配JsonConvert.DeserializeObject,这是尝试获取泛型方法的代码:

return typeof(JsonConvert).GetMethod("DeserializeObject", new Type[] { typeof(string) }).MakeGenericMethod(genericType);
Run Code Online (Sandbox Code Playgroud)

我已经指定我想要将 astring作为其唯一参数的方法,但泛型和非泛型版本都有匹配的参数列表,并且我收到了不明确的匹配错误。

是否可以通过GetMethod这种方式获得通用版本?我知道我可以使用 Linq 并GetMethods()找到它,例如:

var method = typeof(JsonConvert).GetMethods().FirstOrDefault(
            x => x.Name.Equals("DeserializeObject", StringComparison.OrdinalIgnoreCase) &&
            x.IsGenericMethod && x.GetParameters().Length == 1 &&
            x.GetParameters()[0].ParameterType == typeof(string));
Run Code Online (Sandbox Code Playgroud)

但这有点麻烦,一定有更好的方法。

c# generics reflection generic-method

6
推荐指数
2
解决办法
3292
查看次数