简体   繁体   中英

C#: Why don't generics use the most generic type it can when we don't specify one?

For example I now created a this tiny class:

public static class FileSystemInfoComparers<T> where T : FileSystemInfo
{
    public static IEqualityComparer<T> FullName
    {
        get { return new FullNameComparer(); }
    }

    private class FullNameComparer : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)  { return x.FullName == y.FullName;   }
        public int GetHashCode(T obj) { return obj.FullName.GetHashCode(); }
    }
}

I would like it if I could just do

var comparer = FileSystemInfoComparers.FullName;

and have an instance of IEqualityComparer<FileSystemInfo> , since I didn't specify any type and FileSystemInfo is the most generic type T can be. With no type constraint the default type could for example be object or something.

Maybe not the best example, but anyways just got curious here :p

Sounds like a recipe for trouble to me.

In particular, you could easily create a non-generic class called FileSystemInfoComparers with a static property of the same name, and suddenly your code would mean something completely different.

I'd rather keep things simple. (Generics are complicated enough already, and type inference in particular is pretty hairy.)

That is an interesting idea and it could definitely work but consider that it would only work in cases where the generic type argument is constrained with a concrete type.

The .NET compilers are very good at type inference but tend to shy away from making any assumptions. I don't see any reason why this couldn't be done except that it would only work in a small number of highly-specific instances. Since it has no general purpose I would imagine that Microsoft would be less inclined to make a change to support it.

You could possible do this by having a helper class that has the default type you want set. But what you are asking for currently cannot be done in C# 3.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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