简体   繁体   中英

C# 4.0 Optional Parameters - How to Specify Optional Parameter of Type “Guid”?

Here's my method:

public void SomeQuery(string email = "", Guid userId = Guid.Empty)
{
   // do some query
}

userId is giving me an error as it must be a compile-time constant, which i understand. But even when i declare a const:

private const emptyGuid = Guid.Empty;

then change the method signature to:

public void SomeQuery(string email = "", Guid userId = emptyGuid)
{
   // do some query
}

still no love.

What am i missing?

Have you tried setting it to a new instance of Guid ala:

public void SomeQuery(string email = "", Guid userId = new Guid())
{
   // do some query
}

Should do the trick.

maybe it would help (using operator ?? and Guid nullable type)

public void some_method(string name, Guid? guid = null)
{
        _name = name;
        _guid = guid ?? Guid.NewGuid();
}

Wouldn't a better solution be to overload the method with a version that doesn't require the Guid? This would solve the issue, and would be a better design in my opinion. Of course, there may be other constraints that I am unaware of necessitating this design.

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